Vue中怎么進(jìn)行全局守衛(wèi)?下面本篇文章帶大家聊聊Vue中的全局守衛(wèi),希望對(duì)大家有所幫助!
前言:項(xiàng)目中大多數(shù)都是通過路由來進(jìn)行跳轉(zhuǎn)的,但是普遍的都會(huì)進(jìn)行登陸驗(yàn)證后才能進(jìn)入下一頁面,這時(shí)候就需要守衛(wèi)了,本博文主要講解vue中的全局守衛(wèi) 。
全局守衛(wèi)
在main.js
中進(jìn)行配置:
import Vue from 'vue' import App from './App' import router from './router' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' // 全局守衛(wèi) router.beforeEach((to, from, next) => { // 獲取登陸狀態(tài) let isLogin = sessionStorage.getItem('sid') //存儲(chǔ)的sessionStorage的信息,登陸時(shí)使用sessionStorage.setItem('sid', '已登錄') 設(shè)置本地存儲(chǔ)信息 if (to.name === 'login') { // 如果是登錄頁,則跳過驗(yàn)證 next() //鉤子函數(shù) return } if (!isLogin) { // 判斷登陸狀態(tài),sessionStorage不存在的情況下 ElementUI.Message({ //提示消息 message: '請(qǐng)先登錄系統(tǒng)', type: 'error' }) next({ name: 'login' }) // 如果未登錄,則跳轉(zhuǎn)到登錄頁 } else { next() // 如果已經(jīng)登陸,那就可以跳轉(zhuǎn) } })
登錄后復(fù)制
【