vue-routerのrouter-linkを使ってdynamicなlinkの生成
方法①
@app.js
const routes = [
{ path: '/user/:userName', component: Profile,
children: [
{
path: '', component: Activity,
},
{
path: 'follow', component: Follows
},
{
path: 'activity', component: Activity
}
]
},
@componet
<router-link :to="'/user/' + user.name"><router-link>
方法② named-routerを使う
@app.js
const routes = [
{ path: '/user/:userName?', component: Profile,
children: [
{
path: '', component: Activity, name: 'activity'
},
{
path: 'follow', component: Follows
},
{
path: 'activity', component: Activity
}
]
},
@componet
<router-link :to= "{ name: 'activity', params: { userName: user.name } }">
</router-link>
router-linkのparamのuserNameは通常定数にしないとchromeのコンソール上下記のエラーが出る
これを消すにはapp.js側のparameterである:userNameに?を付けてオプショナル扱いにする。
方法②には問題点がある。
/user/userNameでデフォルトでcomponentのActivity.vueを表示させたい場合、
child pathの''にActivityを登録するため
このrouter-linkを辿ると/user/userName/と末尾に/が余分についてしまう。