Vueルーターを使用したVue.jsでのルーティングの概要
提供:Dev Guides
ルーティングは重要なSPAの重要な部分であり、フレームワークのコア部分である必要があります。 Vueの場合、この機能は公式の VueRouterプラグインによって提供されます。 使い方の基本を見てみましょう。
インストールとセットアップ
まず、もちろん、Vueルータープラグインをインストールして有効にする必要があります。 YarnまたはNPMを使用してvue-routerをインストールします。
# Yarn $ yarn add vue-router # NPM $ npm install vue-router --save
次に、プラグインを有効にする必要があります。
main.js
import Vue from 'vue'; import VueRouter from 'vue-router'; import App from './App.vue'; // These are the routes we're going to create. import ourRoutes from './our-routes.js'; Vue.use(VueRouter); // We create the router instance here. const router = new VueRouter({ routes: ourRoutes }); // The usual app stuff goes here. const app = new Vue({ // router, render: h => h(App) }).$mount('#app');
もう一つ。 ルートをレンダリングする場所が必要です。 そのために、私たちは成分。
App.vue
<template> <div id="app"> <h1>Random App Title</h1> <!-- Routes get rendered here --> <router-view></router-view> </div> </template>
ルートの定義
では、いくつかのルートを作成しましょう。 上記のように、まだ存在しないファイルour-routes.jsをインポートしました。 今それを作成しましょう。
ルート定義は、ルートオブジェクトを含む単純な配列です。 このガイドでは、RouteOne.vue
、RouteTwo.vue
、およびRouteOneChild.vue
の3つのターゲットルートがあると想定します。
our-routes.js
import RouteOne from './RouteOne.vue'; import RouteOneChild from './RouteOneChild.vue'; import RouteTwo from './RouteTwo.vue'; export default [ // Redirects to /route-one as the default route. { path: '/', redirect: '/route-one' }, { path: '/route-one', component: RouteOne, // Children is just another route definition of sub-routes. children: [ { // Note: No leading slash. This can trip people up sometimes. path: 'route-one-child', component: RouteOneChild } ] }, { // Route two takes the route parameter "id". // The parameter value can be accessed with $route.params.id in the RouteTwo component. path: '/route-two/:id', component: RouteTwo } ];
ルートへのリンク
あなたはおそらくあなたのアプリのルートにリンクしたいと思うでしょう。 通常を使用する代わりにタグ、使用代わりは。 Router-linkは、静的または動的なtoプロパティを取ります。
<router-link to="/route-one/route-one-child">Text!</router-link> <router-link :to="myRouteTargetString">Dynamic!</router-link>
ドキュメンテーション
ルーティングにはまだまだたくさんのことがあります。まだ始まったばかりです。 詳細については、公式ドキュメントをご覧ください。