Vue-Router

1. 路由配置

默認(rèn)路由跳轉(zhuǎn)
{
     path: '/',
     redirect: '/app'
}
在 new Router時可用的配置參數(shù):
mode : history
base : 基路徑
linkActiveClass : 'active-link' // 被激活樣式(模糊匹配)
linkExactActiveClass : 'exact-active-link' //被激活樣式(精準(zhǔn)匹配)
/**
linkActiveClass和linkExactActiveClass的區(qū)別
使用linkActiveClass,路由跳轉(zhuǎn)為/main和/main/a時否會激活樣式;
使用linkExactActiveClass,路由跳轉(zhuǎn)為/main時會激活樣式,跳轉(zhuǎn)為/main/a時則不會激活樣式。
**/
scrollBehavior(to, from, savedPosition) {//默認(rèn)滾動位置
    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)(導(dǎo)航守衛(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ū)別在于導(dǎo)航被確認(rèn)之前,同時在所有組件內(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) {
    // 在渲染該組件的對應(yīng)路由被 confirm 前調(diào)用
    // 不!能!獲取組件實例 `this`
    // 因為當(dāng)守衛(wèi)執(zhí)行前,組件實例還沒被創(chuàng)建
  },
  beforeRouteUpdate (to, from, next) {
    // 在當(dāng)前路由改變,但是該組件被復(fù)用時調(diào)用
    // 舉例來說,對于一個帶有動態(tài)參數(shù)的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉(zhuǎn)的時候,
    // 由于會渲染同樣的 Foo 組件,因此組件實例會被復(fù)用。而這個鉤子就會在這個情況下被調(diào)用。
    // 可以訪問組件實例 `this`
  },
  beforeRouteLeave (to, from, next) {
    // 導(dǎo)航離開該組件的對應(yīng)路由時調(diào)用
    // 可以訪問組件實例 `this`
  }

4. 異步路由

例:

//路由配置
{
     path: '/describe',
     name: 'Describe',
     component: () => import('...組件路徑')
 }

組件在路由跳轉(zhuǎn)時才渲染
需要安裝babel-plugin-syntax-dynamic-import插件
好處:可以使首屏加載速度更快。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容