1.全局前置守衛(wèi)beforEach(寫在main.js 或router.js添加)
守衛(wèi)方法接收三個參數(shù):
- to:即將要進入的目標路由對象
- from:當前導航正要離開的路由
- next:執(zhí)行下一步
const router = new VueRouter({
routes
})
router.beforeEach((to, from, next) => {
// to將要訪問的路徑
// from代表從哪個路徑跳轉(zhuǎn)而來
// next 是一個函數(shù),表示放行
// next() 放行, next('/login')強制跳轉(zhuǎn)
if (to.path === '/login') return next();
const tokenStr = window.sessionStorage.getItem('token'); //判斷是否存在token
if (!tokenStr) return next('/login');
next();
});
export default router
注意:
當一個導航觸發(fā)時,全局前置守衛(wèi)按照創(chuàng)建順序調(diào)用。守衛(wèi)是異步解析執(zhí)行,此時導航在所有守衛(wèi) resolve 完之前一直處于 等待中。
每個守衛(wèi)方法接收三個參數(shù):
to: Route: 即將要進入的目標 路由對象from: Route: 當前導航正要離開的路由-
next: Function: 一定要調(diào)用該方法來 resolve 這個鉤子。執(zhí)行效果依賴next方法的調(diào)用參數(shù)。next(): 進行管道中的下一個鉤子。如果全部鉤子執(zhí)行完了,則導航的狀態(tài)就是 confirmed (確認的)。next(false): 中斷當前的導航。如果瀏覽器的 URL 改變了(可能是用戶手動或者瀏覽器后退按鈕),那么 URL 地址會重置到from路由對應的地址。next('/')或者next({ path: '/' }): 跳轉(zhuǎn)到一個不同的地址。當前的導航被中斷,然后進行一個新的導航。你可以向next傳遞任意位置對象,且允許設置諸如replace: true、name: 'home'之類的選項以及任何用在router-link的toprop 或router.push中的選項。next(error): (2.4.0+) 如果傳入next的參數(shù)是一個Error實例,則導航會被終止且該錯誤會被傳遞給router.onError()注冊過的回調(diào)。
確保要調(diào)用 next 方法,否則鉤子就不會被 resolved。
2.全局后置鉤子afterEach
- beforeEach是路由跳轉(zhuǎn)前執(zhí)行的,afterEach是路由跳轉(zhuǎn)后執(zhí)行的。
router.afterEach((to,from)=>{
if(to.path === "/news"){
alert("進來news了哦");
}
})
3.路由獨享的守衛(wèi)beforeEnter
- 在路由配置上直接定義 beforeEnter 守衛(wèi)
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
import Home from '../../view/Home.vue'
import Test from '../../view/Test.vue'
import News from '../../view/News.vue'
export default new Router({
routes: [
{
name:"Home",
path:"/",
component:Home,
},
{
name:"Test",
path:"/test",
component:Test,
beforeEnter(to,from,next){
if(to.path==="/test"){
alert("請登錄");
next(false); // 禁止跳轉(zhuǎn)
}else{
next()
}
}
},
{
name:"News",
path:"/news",
component:News
},
{
redirect:"/",
path:"*",
}
],
mode:"history"
})
4.組件內(nèi)的守衛(wèi)
- 它是和data,methods平級的。
- to:即將要進入的目標路由;
- from:當前導航正要離開的路由,from.name 是路由的名稱,對應路由配置中的 name;
- next:一個用來 resolve 當前鉤子的方法,需要調(diào)用該方法來確認或者中斷導航;
beforeRouteLeave(to, from, next) {
// 在渲染該組件的對應路由被 confirm 前調(diào)用
// 不!能!獲取組件實例 `this`
// 因為當守衛(wèi)執(zhí)行前,組件實例還沒被創(chuàng)建
next()
},
beforeRouteEnter(to, from, next) {
// 在當前路由改變,但是該組件被復用時調(diào)用
// 舉例來說,對于一個帶有動態(tài)參數(shù)的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉(zhuǎn)的時候,
// 由于會渲染同樣的 Foo 組件,因此組件實例會被復用。而這個鉤子就會在這個情況下被調(diào)用。
// 可以訪問組件實例 `this`
next()
},
beforeRouteUpdate(to, from, next) {
// 導航離開該組件的對應路由時調(diào)用
// 可以訪問組件實例 `this`
next()
},
data:{},
method: {}