開発者ドキュメント

Vue.jsでネストされたルートを使用する方法

序章

Vue.jsシングルページアプリケーション(SPA)が適度に複雑になると、 Vueルーター、さらにネストされたルートが必要になります。 ネストされたルートにより、コンポーネントが相互にネストされた、より複雑なユーザーインターフェイスが可能になります。

この記事では、ネストされたルートの有用性を強調するVue.jsプロジェクトの例を作成します。

前提条件

このチュートリアルを完了するには、次のものが必要です。

このチュートリアルは、ノードv16.5.0、npm v7.20.0、vue v2.6.14、およびvue-routerv3.5.2で検証されました。

ステップ1—プロジェクトの設定

プロジェクトをすばやく設定するために、この記事では @ vue /cliの使用をお勧めします。

注:この記事では、npxを使用して、@vue/cliのグローバルインストールを回避する方法を採用します。

  1. npx @vue/cli create vue-nested-routes-example

構成オプションの入力を求められたら、手動で機能を選択し、ルーターを含めることができます。

次に、新しく作成されたプロジェクトディレクトリに移動します。

  1. 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.cssindex.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%;
}

変更をファイルに保存します。

次に、ターミナルで次のコマンドを実行します。

  1. npm run serve

Webブラウザでlocalhost:8080にアクセスし、グリッドレイアウトを確認します。

これで、ルーティングを開始できます。

ステップ3—Vueルーティングを適用する

@vue/climain.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
      }
    ]
  },
  // ...
];

// ...

注:子のネストは無限に続く可能性があることに注意してください。

変更をファイルに保存します。

次に、ターミナルで次のコマンドを実行します。

  1. npm run serve

Webブラウザでlocalhost:8080に再度アクセスします。 /nestedルートにアクセスすると、NestedPageOneおよびNestedPageTwo子ルートにアクセスできます。

結論

この記事では、ネストされたルートの有用性を強調するVue.jsプロジェクトの例を作成しました。

このトピックで覚えておくべき他のこと—path: '/location/:id'などの動的セグメントでルートを定義することができます。 次に、それらのルートのビューで、そのIDをthis.$route.paramsとして参照できます。 これは、サイトまたはアプリに表示したい特定のタイプ(ユーザー、写真など)のデータが多い場合に役立ちます。

モバイルバージョンを終了