路由守衛


如果有些頁面需要登錄才能進入 這時候就需要路由守衛了

在router/index.js里面想要攔截的地方加這一段代碼就行了

路由獨享的守衛
在這里插入圖片描述

vue-router路由守衛基本使用
作用
通過路由攔截,來判斷用戶是否登錄,該頁面用戶是否有權限瀏覽
全局路由守衛
全局前置守衛:路由跳轉前調用

router.beforeEach((to,from,next)=>{
console.log(to); // 即將要跳轉的路由
console.log(from); // 即將要離開的路由
next() // 一定要調用 執行下一個鈎子 全部鈎子執行完 跳轉到地址欄上的路由
})

 

 

router.beforeEach((to,from,next)=>{
console.log(to);
console.log(from);
next(false) // 中斷當前路由跳轉
})

router.beforeEach((to,from,next)=>{
console.log(to);
console.log(from);
next('/test') // 跳轉到指定路由 此處代碼寫法錯誤
})

跳轉到指定路由,此處代碼寫法錯誤,會造成死循環直到瀏覽器棧溢出,調用next()的同時也會執行多一次beforeEach

正確寫法是先判斷要離開的路由是什么再跳轉

router.beforeEach((to, from, next) => {
console.log(to);
console.log(from);
if (to.path == "/home") {
next('test');
next({ path: '/test' }) //或者這樣寫
}
});

全局后置守衛:路由跳轉之后再執行

router.afterEach((to,from)=>{
console.log(to);
console.log(from);
})

路由獨享的守衛
在路由配置上直接定義 beforeEnter 守衛

const routes = [
{
path: "/home",
component: () => import(/* webpackChunkName: "user" */ "../views/Home"),
beforeEnter:(to,from,next)=>{
console.log(to);
console.log(from);
next()
}
},
];

效果和beforeEach差不多


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM