Vue?router?路由守衛(wèi)詳解
一、全局前置beforeEach
當 Local Storage 里面存儲的 name 是 zhangsan 的時候, 點擊消息才顯示消息內(nèi)容

1. 全局前置beforeEach
給router添加一個路由守衛(wèi) beforeEach
語法 :
router.beforeEach((to, from, next)=>{})
作用 : 初始化的時候 和 在每一次路由切換之前調(diào)用beforeEach里面的函數(shù)
參數(shù) :
1.to : 目標路由
2.from : 跳轉前的路由
3.next : 放行
2. 實現(xiàn)

二、需求二
如果有很多個路徑都需要做出判斷以后才跳轉, 就需要寫很多判斷的代碼, 判斷結構就會很復雜
這時需要判斷的路由里面就可以放一個meta標簽
meta標簽提供關于HTML文檔的元數(shù)據(jù) (元數(shù)據(jù)指用來描述數(shù)據(jù)的數(shù)據(jù))

這時就可以使用meta里面的標記字段進行判斷

三、全局后置守衛(wèi) afterEach
afterEach 和 beforeEach 使用方法基本一致.
區(qū)別就是afterEach沒有next這個參數(shù)
1. 修改title為自己的title
給每個路由指定自己的title名稱
const router = new VueRouter({
routes: [
{
name: 'home',
path: '/home',
component: Home,
meta: {
title: "首頁"
},
children: [
{
name: "xiaoxi",
path: 'message',
component: Message,
meta: {
title: "消息"
},
children: [
{
name: 'xiangqing',
path: 'detail',
component: Detail,
meta: {
isAuth: true,
title: "消息詳情"
}
}
]
}
]
},
{
path: '/about',
component: About,
meta: {
title: "關于"
}
}
]
})
在 beforEach里面修改title名
router.afterEach((to, from) => {
document.title = to.meta.title || "測試"
})
四、組件內(nèi)守衛(wèi)
1. beforeRouteEnter
通過路由規(guī)則, 進入該組件時被調(diào)用
2. beforeRouteLeave
通過路由規(guī)則, 離開該組件時被調(diào)用
總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內(nèi)容!
相關文章
vue-resource 攔截器(interceptor)的使用詳解
本篇文章主要介紹了vue-resource 攔截器(interceptor)的使用詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-07-07
基于vue+echarts數(shù)據(jù)可視化大屏展示的實現(xiàn)
這篇文章主要介紹了基于vue+echarts數(shù)據(jù)可視化大屏展示的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12

