Vue Router 実装ガイド - 基本設定から応用テクニック

ステップ1: ルーターのインストール

npm install vue-router --save

ルーティング設定の基本構文

router/index.js での設定

import Vue from "vue";
import Router from "vue-router";
import HelloWorld from "@/components/HelloWorld";

Vue.use(Router);

export default new Router({
  routes: [
    {
      path: "/sample",
      component: SampleComponent,
      meta: { requiresAuth: true },
      children: [
        { path: "child1", component: Child1 },
        { path: "child2", component: Child2 }
      ]
    }
  ]
});

main.js でのルーター統合

import router from "./router";

new Vue({
  el: "#app",
  router,
  store,
  components: { App },
  template: "<App/>"
});

実践的なコード例

コンポーネント定義

<template>
  <div class="page">
    <h3>ルーティング基本</h3>
  </div>
</template>

<script>
export default {
  name: "Page",
  data() {
    return {};
  }
};
</script>

<style scoped>
</style>

ルーティング定義

import Vue from "vue";
import Router from "vue-router";
import Page from "@/components/Page";

Vue.use(Router);

export default new Router({
  routes: [
    { path: "/page", component: Page }
  ]
});

ナビゲーションの実装

router-link コンポーネントを使用して画面遷移を実現します。

<!-- 直接パス指定 -->
<router-link to="/lifecycle">ライフサイクル</router-link>

<!-- 動的パス指定 -->
<router-link :to="vuexPath">Vuex</router-link>

data() {
  return {
    vuexPath: "/vuex"
  };
}

子ルーティングの設定

<router-link to="/parent/child1">子ルート1</router-link>
<router-link to="/parent/child2">子ルート2</router-link>
<router-view></router-view>

// ルーティング設定
routes: [
  {
    path: "/parent",
    component: ParentComponent,
    children: [
      { path: "child1", component: Child1 },
      { path: "child2", component: Child2 }
    ]
  }
]

子ルートのパスに先頭の / を付けない場合、親ルートからの相対パスとなります。/ を付けるとルートからの絶対パスとして解釈されます。

パラメータの受け渡し方法

1. ルートパラメータ($route.params)

<!-- 直接指定 -->
<router-link to="/parent/child2/12345">子ルート2</router-link>

<!-- スクリプトから -->
methods: {
  navigateToChild(id) {
    this.$router.push({
      path: `/parent/child1/${id}`
    });
  }
},
mounted() {
  console.log(this.$route.params.id);
}

// ルート定義
{ path: "child2/:id", component: Child2 }

2. params オブジェクト($route.params)

<p @click="goToChild('222222')">子ルート1へ</p>

methods: {
  goToChild(id) {
    this.$router.push({
      name: "child1",
      params: { id: id }
    });
  }
},
mounted() {
  console.log(this.$route.params.id);
}

// ルート定義
children: [
  {
    path: "child1/:id",
    name: "child1",
    component: Child1
  }
]

params を使用した場合、URL にパラメータは表示されません(query と対照的です)。

3. query パラメータ($route.query)

<!-- 直接指定 -->
<router-link :to="{ path: '/parent/child1', query: { id: '000' }}">
  子ルート1
</router-link>

<!-- スクリプトから -->
methods: {
  goToChild(id) {
    this.$router.push({
      path: "/parent/child1",
      query: { id: id }
    });
  }
},
mounted() {
  console.log(this.$route.query.id);
}

query を使用すると URL に ?id=value の形式でパラメータが表示されます。

ナビゲーションメソッド

$router.go(n)

history スタック内を指定されたステップ数だけ前進または後退します。

methods: {
  forward() {
    this.$router.go(1);
  },
  back() {
    this.$router.go(-1);
  }
}

$router.push(location)

新しいエントリを history スタックに追加します。ブラウザの戻るボタンで前の画面に戻れます。

$router.replace(location)

push と似ていますが、新しいエントリを追加する代わりに現在のエントリを置き換えます。

エイリアスとリダイレクト

エイリアス(alias)

別のパスから同じルートにアクセスできるようにします。

export default new Router({
  routes: [
    {
      path: "/",
      alias: "/home",
      component: HomeComponent
    }
  ]
});

/home にアクセスすると URL は /home のままですが、/ のルートがマッチします。

リダイレクト(redirect)

指定されたパスにアクセスした際に、別のパスへ自動的に転送します。

export default new Router({
  routes: [
    {
      path: "/",
      redirect: "/dashboard"
    },
    { path: "/dashboard", component: DashboardComponent }
  ]
});

遅延ローディング(Lazy Loading)

export default new Router({
  routes: [
    {
      path: "/",
      component: (resolve) => require(["@/components/Home.vue"], resolve),
      children: [
        { path: "child1/:id", name: "child1", component: Child1 },
        { path: "child2/:param", component: Child2 }
      ]
    },
    {
      path: "/dashboard",
      component: (resolve) => require(["@/components/Dashboard.vue"], resolve)
    }
  ]
});

ナビゲーションガード(ルートフック)

beforeRouteEnter(to, from, next) {
  // コンポーネントがレンダリングされる前に呼ばれます
  // この段階では 'this' にアクセスできません
  next(vm => {
    // 'vm' 経由でコンポーネントインスタンスにアクセス可能
  });
},

beforeRouteUpdate(to, from, next) {
  // 同じコンポーネントが再利用される際に呼ばれます
  // (例:/foo/:id で id が変更された場合)
  // 'this' にアクセス可能
  next();
},

beforeRouteLeave(to, from, next) {
  // このルートから離れる際に呼ばれます
  // 'this' にアクセス可能
  next();
}

タグ: Vue Router SPA ルーティング ナビゲーションガード Lazy Loading

7月15日 00:54 投稿