はじめに
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 }
]
})
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/
以上