欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue中router.beforeEach()的簡單用法舉例

 更新時(shí)間:2023年01月05日 14:14:47   作者:大象與小螞蟻的生活  
router.beforeEach()一般用來做一些進(jìn)入頁面的限制,比如沒有登錄,就不能進(jìn)入某些頁面,只有登錄了之后才有權(quán)限查看某些頁面,下面這篇文章主要給大家介紹了關(guān)于vue中router.beforeEach()的簡單用法舉例,需要的朋友可以參考下

導(dǎo)航守衛(wèi) 主要是通過跳轉(zhuǎn)或取消得方式守衛(wèi)導(dǎo)航

在前端路由跳轉(zhuǎn)中,路由跳轉(zhuǎn)前都是會(huì)經(jīng)過beforeEach,而beforeEach可以通過next來控制到底去哪個(gè)路由。根據(jù)這個(gè)特性我們就可以在beforeEach中設(shè)置一些條件來控制路由的重定向。

常見的使用場景有:

1、驗(yàn)證用戶是否登錄(若未登錄,且當(dāng)前非登錄頁面,則自動(dòng)重定向登錄頁面);

2、用戶權(quán)限;

3、用戶輸入的路路徑是否存在,不存在的情況下如何處理,重定向到哪個(gè)頁面。

此處呢我使用一個(gè)簡單的例子:

當(dāng)用戶輸入的路徑不存在的情況下,將其重定向到‘/’路徑來說明beforeEach是如何控制路由的。

話不多說,直接看下邊如何實(shí)現(xiàn)的(這里我以創(chuàng)建一個(gè)名為router-be的項(xiàng)目為例)。

第一步 : 規(guī)定進(jìn)入路由是否需要權(quán)限

@/router/index.js

import A from '@/components/a'
{
	path : '/a',
	name : 'a',
	component : A,
	meta : {  // 加一個(gè)自定義obj
		requireAuth : true   // 參數(shù) true 代表需要登陸才能進(jìn)入 A
	}
}

第二步 : 使用vuex 整一個(gè)useid

@/assets/store.js

//使用vuex三步走
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//這個(gè)理論來說
const store = new Vuex.Store({
	state:{
		userId : ''
	}
})

export default store

第三步 : 使用router.beforeEach()

思路:【
	如果(進(jìn)入這個(gè)路由需要權(quán)限){
	
		如果(能獲取到這個(gè)用戶的userID){
			就讓這個(gè)用戶進(jìn)入這個(gè)路由
		}否則{
			就讓這個(gè)用戶進(jìn)入b這個(gè)頁面
		}
		
	} 即將進(jìn)入的路由不需要權(quán)限就能進(jìn)入 {
	
		就讓這個(gè)用戶進(jìn)入這個(gè)路由
		
	}
】
對應(yīng)代碼:
import store from '@/assets/store'   //把這個(gè)userId獲取過來
router.beforeEach((to,from,next)=>{
	if(to.meta.requireAuth){
		if(store.state.userId){
			next()
		}else{
			next({path:'/b'})
		}
	}else{
		next()
	}
})

實(shí)現(xiàn)原理

  • constrouter=newVueRouter({…})
  •  router.beforeEach((to,from,next)=>{// …})
  •  每個(gè)守衛(wèi)方法接受三個(gè)參數(shù) :

1.to => route : 即將進(jìn)入的目標(biāo)路由對象

2.from => route : 當(dāng)前導(dǎo)航正要離開的路由

3.next => function: 一定要調(diào)用該方法來 resolve這個(gè)鉤子,執(zhí)行效果以來 next 方法的調(diào)用參數(shù)

第四步

  • 上一步 /b 路由為 登陸頁面
  • 當(dāng)進(jìn)入A 頁面之前,需要先請求接口,獲取是否有登錄,然后把userId存在vuex 的state 中
  • 當(dāng)沒有userId 時(shí),則在登錄之后,存一個(gè)userId 到state 里

第五步 項(xiàng)目中使用

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);
  }

  //驗(yàn)證權(quán)限
  if (to.meta.permId && !hasPerms(to.meta.permId)) {
    console.log("no auth", to, from);
    return next(LoginPage.path);
  }

  //驗(yàn)證是否登錄
  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();
});

權(quán)限

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;
    }

    // 判斷是否有權(quán)限
    const hasAuthority = to.meta.permId && hasPerms(to.meta.permId);

    if (hasAuthority) { // 權(quán)限驗(yàn)證
      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) {
      // 設(shè)置頁面`title`
      document.title = `一立科技 - ${to.meta.label}`;
    }
  });
}

總結(jié)

到此這篇關(guān)于vue中router.beforeEach()的簡單用法舉例的文章就介紹到這了,更多相關(guān)vue router.beforeEach()用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論