溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

vue路由守衛(wèi)如何限制前端頁面訪問權(quán)限

發(fā)布時(shí)間:2021-07-26 14:03:07 來源:億速云 閱讀:125 作者:小新 欄目:web開發(fā)

這篇文章主要介紹vue路由守衛(wèi)如何限制前端頁面訪問權(quán)限,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

首先需要寫一個(gè)路由守衛(wèi),它的原理是每次路由發(fā)生變化時(shí)觸發(fā)具體寫法如下:

router.beforeEach((to, from, next) => {
  next()
})

beforeEach函數(shù)有三個(gè)參數(shù):

to:即將進(jìn)入的路由對(duì)象

from:當(dāng)前導(dǎo)航即將離開的路由

next,進(jìn)行管道中的一個(gè)鉤子,如果執(zhí)行完了,則導(dǎo)航的狀態(tài)就是 confirmed (確認(rèn)的);否則為false,終止導(dǎo)航。

使用案例

限制登陸功能,具體實(shí)現(xiàn)思路:每次跳轉(zhuǎn)路由是判斷本地 localStorage.getItem('token') 狀態(tài)

首先找到router/index.js如下

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
 
const router = new Router({
 routes: [{
   path: '/',
   name: 'HelloWorld',
   component: HelloWorld
  },
  {
   path: '/login',
   name: 'login',
   component: login
  }
 ]
})
//下面是重點(diǎn) 
router.beforeEach((to, from, next) => {
 let token = localStorage.getItem('token') 
 if (to.path == '/login') {
  next()
 } else {
  if (token == '' || token == null) {
   next('/login');
  } else {
   next()
  }
 }
 
})
 
export default router;

解釋:index.js寫成如上形式,用const router 接受 new Router對(duì)象,最后export暴露出去

router.beforeEach 在每次路由跳轉(zhuǎn)出發(fā)

let token = localStorage.getItem('token') 獲取本地沒有沒token 如果沒有就跳到login頁面 很簡單的邏輯

以上是“vue路由守衛(wèi)如何限制前端頁面訪問權(quán)限”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

vue
AI