Vue.jsでネストされたルートを使用する方法
序章
Vue.jsシングルページアプリケーション(SPA)が適度に複雑になると、 Vueルーター、さらにネストされたルートが必要になります。 ネストされたルートにより、コンポーネントが相互にネストされた、より複雑なユーザーインターフェイスが可能になります。
この記事では、ネストされたルートの有用性を強調するVue.jsプロジェクトの例を作成します。
前提条件
このチュートリアルを完了するには、次のものが必要です。
- Node.jsはローカルにインストールされます。これは、Node.jsのインストール方法とローカル開発環境の作成に従って実行できます。
- Vue.jsプロジェクトのセットアップおよびVue.jsコンポーネントの使用にある程度精通していると有益な場合があります。
このチュートリアルは、ノードv16.5.0、npm
v7.20.0、vue
v2.6.14、およびvue-router
v3.5.2で検証されました。
ステップ1—プロジェクトの設定
プロジェクトをすばやく設定するために、この記事では @ vue /cliの使用をお勧めします。
注:この記事では、npx
を使用して、@vue/cli
のグローバルインストールを回避する方法を採用します。
npx @vue/cli create vue-nested-routes-example
構成オプションの入力を求められたら、手動で機能を選択し、ルーターを含めることができます。
次に、新しく作成されたプロジェクトディレクトリに移動します。
cd vue-nested-routes-example
この時点で作成時にVueルーターをインストールしなかった場合は、プロジェクトに今すぐ追加できます。
ステップ2—アプリケーションの構築
次のCSSは、ユーザーインターフェイスの要素の配置に役立ちます。
'public
ディレクトリの下に、grid.css
ファイルを作成します。
public / grid.css
.row1 { grid-row-start: 1; grid-row-end: 2; } .row12 { grid-row-start: 1; grid-row-end: 3; } .row123 { grid-row-start: 1; grid-row-end: 4; } .row2 { grid-row-start: 2; grid-row-end: 3; } .row23 { grid-row-start: 2; grid-row-end: 4; } .row3 { grid-row-start: 3; grid-row-end: 4; } .col1 { grid-column-start: 1; grid-column-end: 2; } .col12 { grid-column-start: 1; grid-column-end: 3; } .col123 { grid-column-start: 1; grid-column-end: 4; } .col1234 { grid-column-start: 1; grid-column-end: 5; } .col2 { grid-column-start: 2; grid-column-end: 3; } .col23 { grid-column-start: 2; grid-column-end: 4; } .col234 { grid-column-start: 2; grid-column-end: 5; } .col3 { grid-column-start: 3; grid-column-end: 4; } .col34 { grid-column-start: 3; grid-column-end: 5; } .col4 { grid-column-start: 4; grid-column-end: 5; }
CSSグリッドを利用します。
grid.css
をindex.html
に追加します。
public / index.html
<!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <link rel="icon" href="<%= BASE_URL %>favicon.ico"> <link rel="stylesheet" href="grid.css"> <title><%= htmlWebpackPlugin.options.title %></title> </head> <body> <noscript> <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"></div> <!-- built files will be auto injected --> </body> </html>
次に、@vue/cli
が作成したデフォルトファイルにいくつか変更を加えましょう。
コードエディタでApp.vue
を開きます。 また、App.vue
のHTMLマークアップに次の変更を加えます。
src / App.vue
<template> <div id="app"> <h1 class="row1 col12">Example</h1> <a class="row1 col3">About</a> <a class="row1 col4">Nested Pages</a> <div class="row2 col234"></div> </div> </template>
そしてApp.vue
のCSSスタイリング:
src / App.vue
html, body { height: 100vh; width: 100vw; padding: 0; margin: 0; } #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; color: #2c3e50; padding: 2%; height: 100%; display: grid; grid-template-rows: 20% 80%; grid-template-columns: 25% 25% 25% 25%; }
変更をファイルに保存します。
次に、ターミナルで次のコマンドを実行します。
npm run serve
Webブラウザでlocalhost:8080
にアクセスし、グリッドレイアウトを確認します。
これで、ルーティングを開始できます。
ステップ3—Vueルーティングを適用する
@vue/cli
はmain.js
ファイルを作成します。
src / main.js
import Vue from 'vue' import App from './App.vue' import router from './router' Vue.config.productionTip = false new Vue({ router, render: h => h(App) }).$mount('#app')
そしてrouter/index.js
ファイル:
src / router / index.js
import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/Home.vue' Vue.use(VueRouter) const routes = [ { path: '/', name: 'Home', component: Home }, { path: '/about', name: 'About', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/About.vue') } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router
また、views
ディレクトリ内のHome.vue
およびAbout.vue
ファイル。
App.vue
に戻り、Aboutのアンカータグをto="/about"
の属性を持つ<router-link>
タグに変更してみましょう。 次に、2番目のdiv
を<router-view>
タグに変更します。 グリッド配置クラスの属性はそのままにしておいてください。
src / App.vue
<template> <div id="app"> <h1 class="row1 col12">Example</h1> <router-link to="/about" class="row1 col3">About</router-link> <a class="row1 col4">Nested Pages</a> <router-view class="row2 col234" /> </div> </template>
これで、Aboutページでルーティングが処理された機能的なサイトスケルトンができました。
ステップ4—ネストされたビューを構築する
ここではルーティング機能に重点を置いているため、スタイリングに煩わされることはありません。 それでも、Nested
ページはより複雑に見えます。
まず、views
ディレクトリにNestedPages.vue
ファイルを作成します。
src / views / NestedPages.vue
<template> <div id="nested"> <h2 class="row1">Nested Pages</h2> </div> </template> <script> export default { name: 'NestedPages' } </script> <style scoped> div { text-align: center; } </style>
そしてそれをrouter/index.js
で参照してください:
src / router / index.js
import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/Home.vue' import NestedPages from '../views/NestedPages.vue' Vue.use(VueRouter) const routes = [ { path: '/', name: 'Home', component: Home }, { path: '/about', name: 'About', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ '../views/About.vue') }, { path: '/nested', component: NestedPages } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router
また、最終的にNestedPages.vue
にネストされる次の2つのコンポーネントを作成します。
NestedPageOne.vue
ファイルを作成します。
src / components / NestedPageOne.vue
<template> <div> <p>Nested Page One</p> </div> </template> <script> export default { name: 'NestedPageOne' } </script> <style scoped> </style>
同様のNestedPageTwo.vue
ファイルを作成します。
src / components / NestedPageTwo.vue
<template> <div> <p>Nested Page Two</p> </div> </template> <script> export default { name: 'NestedPageTwo' } </script> <style scoped> </style>
最後に、App.vue
に再度アクセスし、<router-link>
を使用するように[ネストされたページ]リンクを更新します。
src / App.vue
<template> <div id="app"> <h1 class="row1 col12">Example</h1> <router-link to="/about" class="row1 col3">About</router-link> <router-link to="/nested" class="row1 col4">Nested Pages</router-link> <router-view class="row2 col234" /> </div> </template>
この時点で、新しいnested
ルートと2つの新しいコンポーネントがあります。
ステップ5—ネストされた子ルートの構成
NestedPages.vue
に再度アクセスし、ネストされたページ1とネストされたページ2に<router-link>
を追加します。
src / views / NestedPages.vue
<template> <div id="nested"> <h2 class="row1">Nested Pages</h2> <div class="flex-container row2"> <router-link to="/nested/one">Nested Page One</router-link> <router-link to="/nested/two">Nested Page Two</router-link> </div> <router-view class="row3" /> </div> </template> <script> export default { name: 'NestedPages' } </script> <style scoped> div { text-align: center; } #nested { display: grid; grid-template-rows: 20% 40% 40%; } .flex-container { display: flex; justify-content: space-around; } </style>
それでは、router/index.js
を更新して、children
を使用してこれらのネストされたルートを参照しましょう。
router / index.js
// ... import NestedPageOne from '../components/NestedPageOne.vue' import NestedPageTwo from '../components/NestedPageTwo.vue' // ... const routes = [ // ... { path: '/nested', component: NestedPages, children: [ <^>{ path: '/nested/one', component: NestedPageOne }, { path: '/nested/two', component: NestedPageTwo } ] }, // ... ]; // ...
注:子のネストは無限に続く可能性があることに注意してください。
変更をファイルに保存します。
次に、ターミナルで次のコマンドを実行します。
npm run serve
Webブラウザでlocalhost:8080
に再度アクセスします。 /nested
ルートにアクセスすると、NestedPageOne
およびNestedPageTwo
子ルートにアクセスできます。
結論
この記事では、ネストされたルートの有用性を強調するVue.jsプロジェクトの例を作成しました。
このトピックで覚えておくべき他のこと—path: '/location/:id'
などの動的セグメントでルートを定義することができます。 次に、それらのルートのビューで、そのIDをthis.$route.params
として参照できます。 これは、サイトまたはアプリに表示したい特定のタイプ(ユーザー、写真など)のデータが多い場合に役立ちます。