vue-router 使用 本教程源于官網(wǎng)https://router.vuejs.org/zh/guide/#javascript 的總結(jié) 提煉
vue-router(一)
vue調(diào)用如下
this.route 訪問當(dāng)前路由
(一) 動(dòng)態(tài)路由
1 動(dòng)態(tài)路由匹配
eg: /user/foo 和 user/bar 倆個(gè)路由使用同一個(gè)組件
routes: [
// 動(dòng)態(tài)路徑參數(shù) 以冒號(hào)開頭
{ path: '/user/:id', component: User }
]
匹配了怎么怎么到 /user/:id 的 id值呢
在組件下調(diào)用 $route.params.id 查詢
有趣玩法: /user/:username/post/:post_id
2 響應(yīng)路由參數(shù)的變化
同一組復(fù)用固然高效齿坷,但是不會(huì)出發(fā)vue的mount等函數(shù)
方法 1:利用watch
export default( {
watch: {
'$route' (to, from) {
// 對(duì)路由變化作出響應(yīng)...
}
}
})
方法 2: 2.2 中引入的 beforeRouteUpdate
路由守衛(wèi)
export default( {
beforeRouteUpdate (to, from, next) {
// 路由更新前調(diào)用
}
})
3 捕獲所有路由或 404 Not found 路由
- 類似正則的匹配 具體匹配規(guī)則 參照 https://github.com/pillarjs/path-to-regexp/tree/v1.7.0
{
// 會(huì)匹配所有路徑
path: '*'
}
{
// 會(huì)匹配以 `/user` 開頭的任意路徑
path: '/user*'
}
當(dāng)路由時(shí)通過*匹配得出的 那么會(huì)有一個(gè)
this.$route.params.pathMatch 指向被匹配的部分
eg: 路由 /user/ffffff 則 this.$route.params.pathMatch 值時(shí) /ffffff
4 匹配優(yōu)先級(jí)
那個(gè)寫在前面那個(gè)優(yōu)先級(jí)高
(二)嵌套路由
及寫子路由方法
const router = new VueRouter({
routes: [
// 這里時(shí) /:id 下的子路由
{ path: '/user/:id', component: User,
children: [
{
path: 'profile', // 不是以/ 開頭
component: UserProfile
name:"",
meta:{}
},
]
}
]
})