vue中關于router.beforeEach()的用法
router.beforeEach()用法
導航守衛(wèi) 主要是通過跳轉或取消得方式守衛(wèi)導航
在前端路由跳轉中,路由跳轉前都是會經(jīng)過beforeEach,而beforeEach可以通過next來控制到底去哪個路由。
根據(jù)這個特性我們就可以在beforeEach中設置一些條件來控制路由的重定向。
常見的使用場景有
1、驗證用戶是否登錄(若未登錄,且當前非登錄頁面,則自動重定向登錄頁面);
2、用戶權限;
3、用戶輸入的路路徑是否存在,不存在的情況下如何處理,重定向到哪個頁面。
此處呢我使用一個簡單的例子
當用戶輸入的路徑不存在的情況下,將其重定向到‘/’路徑來說明beforeEach是如何控制路由的。
話不多說,直接看下邊如何實現(xiàn)的(這里我以創(chuàng)建一個名為router-be的項目為例)。
第一步 : 規(guī)定進入路由是否需要權限
@/router/index.js
import A from '@/components/a'
{
path : '/a',
name : 'a',
component : A,
meta : { // 加一個自定義obj
requireAuth : true // 參數(shù) true 代表需要登陸才能進入 A
}
}
第二步 : 使用vuex 整一個useid
@/assets/store.js
//使用vuex三步走
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//這個理論來說
const store = new Vuex.Store({
state:{
userId : ''
}
})
export default store
第三步 : 使用router.beforeEach()
思路:【
如果(進入這個路由需要權限){
如果(能獲取到這個用戶的userID){
就讓這個用戶進入這個路由
}否則{
就讓這個用戶進入b這個頁面
}
} 即將進入的路由不需要權限就能進入 {
就讓這個用戶進入這個路由
}
】
對應代碼:
import store from '@/assets/store' //把這個userId獲取過來
router.beforeEach((to,from,next)=>{
if(to.meta.requireAuth){
if(store.state.userId){
next()
}else{
next({path:'/b'})
}
}else{
next()
}
})
實現(xiàn)原理
constrouter=newVueRouter({…})
router.beforeEach((to,from,next)=>{// …})每個守衛(wèi)方法接受三個參數(shù) :
- 1.to => route : 即將進入的目標路由對象
- 2.from => route : 當前導航正要離開的路由
- 3.next => function: 一定要調(diào)用該方法來 resolve這個鉤子,執(zhí)行效果以來 next 方法的調(diào)用參數(shù)
第四步
- 上一步 /b 路由為 登陸頁面
- 當進入A 頁面之前,需要先請求接口,獲取是否有登錄,然后把userId存在vuex 的state 中
- 當沒有userId 時,則在登錄之后,存一個userId 到state 里
第五步 項目中使用
router.beforeEach((to, from, next) => {
console.log(to);
// DEBUG: 測試
return next();
const { ldomain } = to.query;
if (ldomain) {
document.domain = ldomain;
}
const { LoginPage } = byskConfig;
if (!router.getMatchedComponents(to.path).length) {
console.log("not page", to, from);
return next(byskConfig.NotFoundPage.path);
}
//驗證權限
if (to.meta.permId && !hasPerms(to.meta.permId)) {
console.log("no auth", to, from);
return next(LoginPage.path);
}
//驗證是否登錄
if (to.meta.permId && !getCookie("sid")) {
console.log("no login & signout", to, from);
return next(LoginPage.path);
}
if (to.matched.length) {
let parentRoute = to.matched[to.matched.length - 1].parent;
if (
parentRoute &&
parentRoute.meta.hasOwnProperty("redirect") &&
parentRoute.meta.redirect !== to.path) {
parentRoute.meta.redirect = to.path;
}
}
next();
});
權限
export function setupPermissionGuard(router) {
router.beforeEach(async (to, from, next) => {
const { state, commit, dispatch } = store;
// TODO: 404 的處理
// 不需要登錄,可訪問
if (to.meta.ignoreAuth === true) {
next();
return;
}
// TODO: 白名單
// 刷新重新登錄
if (!state.appToken) {
await dispatch('relogin');
}
// 處理token
const hasToken = !!state.appToken;
if (!hasToken) { // 未登陸,或過期
// 重定向到登錄頁
const redirectData = {
path: LOGIN_PATH,
replace: true,
};
next(redirectData);
return;
}
// 判斷是否有權限
const hasAuthority = to.meta.permId && hasPerms(to.meta.permId);
if (hasAuthority) { // 權限驗證
if (to.meta.ignoreKeepAlive !== true) {
// 頁面需要緩存, 添加到緩存
const { cachePages } = state;
const { matched } = to;
commit('setCachePages', [...cachePages, ...matched.slice(1)]);
}
next();
return;
}
next(from.path);
// next();
});
router.afterEach((to) => {
if (to.meta?.label) {
// 設置頁面`title`
document.title = `一立科技 - ${to.meta.label}`;
}
});
}


總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
vue中watch和computed為什么能監(jiān)聽到數(shù)據(jù)的改變以及不同之處
這篇文章主要介紹了vue中watch和computed為什么能監(jiān)聽到數(shù)據(jù)的改變以及不同之處,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-12-12
Vue-router優(yōu)化import引入過多導致index文件臃腫問題
這篇文章主要為大家介紹了Vue-router優(yōu)化import引入過多導致index文件臃腫問題解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08

