1. 路由配置
默認路由跳轉(zhuǎn)
{
path: '/',
redirect: '/app'
}
在 new Router時可用的配置參數(shù):
mode : history
base : 基路徑
linkActiveClass : 'active-link' // 被激活樣式(模糊匹配)
linkExactActiveClass : 'exact-active-link' //被激活樣式(精準匹配)
/**
linkActiveClass和linkExactActiveClass的區(qū)別
使用linkActiveClass展融,路由跳轉(zhuǎn)為/main和/main/a時否會激活樣式析砸;
使用linkExactActiveClass,路由跳轉(zhuǎn)為/main時會激活樣式壶笼,跳轉(zhuǎn)為/main/a時則不會激活樣式顷编。
**/
scrollBehavior(to, from, savedPosition) {//默認滾動位置
if(savedPosition) {
return savedPosition
} else {
return {x:0,y:0}
}
}
fallback: false //單頁變多頁
2.路由傳參
Vue路由傳參的幾種方式
$router.push 實現(xiàn)path攜帶參數(shù)的跳轉(zhuǎn):
this.$router.push({
path: `/describe/${id}`,
})
//路由配置:
{
path: '/describe/:id',
name: 'Describe',
component: Describe
}
//子組件中獲取參數(shù)
$route.params.id
通過params傳參:
this.$router.push({
name: 'Describe',
params: {
id: id
}
})
//路由配置
{
path: '/describe',
name: 'Describe',
component: Describe
}
//子組件中獲取參數(shù)
$route.params.id
通過使用path來匹配路由堕义,然后通過query來傳遞參數(shù)上陕。這種情況下 query傳遞的參數(shù)會顯示在url后面?id=扬跋?
this.$router.push({
path: '/describe',
query: {
id: id
}
})
//路由配置
{
path: '/describe',
name: 'Describe',
component: Describe
}
//子組件中獲取參數(shù)
$route.query.id
3. 路由守衛(wèi)(導航守衛(wèi))
即路由跳轉(zhuǎn)前做一些驗證阶捆。
全局守衛(wèi)
每次路由跳轉(zhuǎn)都能夠觸發(fā)三個function:
router.beforeEach((to, from, next) => {
//全局前置守衛(wèi)
//路由跳轉(zhuǎn)前攔截
})
router.beforeResolve((to, from, next) => {
//全局解析守衛(wèi)
//跟beforeEach相似揖盘,區(qū)別在于導航被確認之前,同時在所有組件內(nèi)守衛(wèi)和異步路由組件被解析之后逾柿,解析守衛(wèi)就被調(diào)用
})
router.afterEach((to, from) => {
//全局后置鉤子
})
組件內(nèi)守衛(wèi)
組件內(nèi)有三個鉤子函數(shù)可進行路由守衛(wèi):
beforeRouteEnter (to, from, next) {
// 在渲染該組件的對應路由被 confirm 前調(diào)用
// 不庶溶!能!獲取組件實例 `this`
// 因為當守衛(wèi)執(zhí)行前垒棋,組件實例還沒被創(chuàng)建
},
beforeRouteUpdate (to, from, next) {
// 在當前路由改變卒煞,但是該組件被復用時調(diào)用
// 舉例來說,對于一個帶有動態(tài)參數(shù)的路徑 /foo/:id叼架,在 /foo/1 和 /foo/2 之間跳轉(zhuǎn)的時候畔裕,
// 由于會渲染同樣的 Foo 組件,因此組件實例會被復用乖订。而這個鉤子就會在這個情況下被調(diào)用扮饶。
// 可以訪問組件實例 `this`
},
beforeRouteLeave (to, from, next) {
// 導航離開該組件的對應路由時調(diào)用
// 可以訪問組件實例 `this`
}
4. 異步路由
例:
//路由配置
{
path: '/describe',
name: 'Describe',
component: () => import('...組件路徑')
}
組件在路由跳轉(zhuǎn)時才渲染
需要安裝babel-plugin-syntax-dynamic-import插件
好處:可以使首屏加載速度更快。