LoginSignup
7
12

More than 3 years have passed since last update.

Vue基礎:Routerの書き方

Posted at

はじめに

Vue.jsのRouterの書き方はいくつかがありますので、まとめてみます。

1. インストール

npm install vue-router

2. appに導入

const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

const router = new VueRouter({
  routes
})

const app = new Vue({
  router
}).$mount('#app')

詳細:https://router.vuejs.org/ja/guide/#javascript

HTMLでは下記のように記載できます。

 <router-link to="/foo">Go to Foo</router-link>
 <router-link to="/bar">Go to Bar</router-link>

JSでは下記のように記載できます。

// URLのパラメータから情報を取得する。/user/xxxxx
const userId = this.$route.params.userId

// URLのQueryから情報を取得する。 /user?userId=xxxx
const userId = this.$route.query.userId

// ページ遷移する
window.history.length > 1
        ? this.$router.go(-1)
        : this.$router.push('/')

3. 動的ルートマッチング

定義サンプル:

const router = new VueRouter({
  routes: [
    // コロン
    { path: '/user/:userId', component: User }
  ]
})

image.png

4. ネストされたルート

サイトにあるサンプルです。マイページの実装ではこのパターンを利用できそうです。

const User = {
  template: `
    <div class="user">
      <h2>User {{ $route.params.id }}</h2>
      <router-view></router-view>
    </div>
  `
}
const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User,
      children: [
        {
          // /user/:id/profile がマッチした時に
          // UserProfile は User の <router-view> 内部で描画されます
          path: 'profile',
          component: UserProfile
        },
        {
          // /user/:id/posts がマッチした時に
          // UserPosts は User の <router-view> 内部で描画されます
          path: 'posts',
          component: UserPosts
        }
      ]
    }
  ]
})

URL: https://router.vuejs.org/ja/guide/essentials/nested-routes.html

5. ページ遷移の記載仕方

HTMLタグで定義例

<router-link :to="{ name: 'user', params: { userId: 'xxxxx' }}">User</router-link>

JS記載

/////////////////////////
// 文字列パス
// /home
router.push('home')

// オブジェクト
// /home
router.push({ path: 'home' })

// 名前付きルート
// /user/xxxxx
router.push({ name: 'user', params: { userId: 'xxxxx' } })

// query
// /myapge?userId=xxxxx
router.push({ path: 'mypage', query: { userId: 'xxxxx' } })

※一点注意したいものがあります。paramsの動作です。下記の流れで説明します。

  • router定義例(動的パラメータはuserIdを定義)
const router = new VueRouter({
  routes: [
    // コロン
    { path: '/user/:userId', component: User }
  ]
})

  • ページ遷移
// paramsにrouterに存在しないパラメータuserName,ageのデータも送付
this.$router.push({ name: 'user', params: { userId: 'xxxxx', userName: 'tanaka', age: '30' } })
  • 遷移先ページの初期化

this.$route.params.userId,this.$route.params.userName,this.$route.params.ageでもデータが取得できます。
ただし、F5で画面リフレッシュをすると、this.$route.params.userName,this.$route.params.ageが取得できません。
この場合は、paramsではなく、queryで渡すことで回避できます。

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

リダイレクト

URL「/a」をアクセスすると、「/b」にRedirestします。

const router = new VueRouter({
  routes: [
    { path: '/a', redirect: '/b' }
  ]
})

エイリアス

URL「/a」と「/b」は同じ動作になります。

const router = new VueRouter({
  routes: [
    { path: '/a', component: A, alias: '/b' }
  ]
})

参考URL:https://router.vuejs.org/ja/

以上

7
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
12