登陸頁面路徑 '/login'
首頁路徑 '/'
beforeEach鉤子函數(shù)筑悴,是一個全局的before鉤子函數(shù)。before each 在每一個路由改變的時候都執(zhí)行一遍
處理頁面訪問權(quán)限驗證,在login頁面使用sessionStorage配合vuex
1.登陸頁面
login(){
this.$validator.validateAll().then(result=>{
if(result){
console.log("成功")
this.$store.commit('login_in', this.mobile)
// 跳轉(zhuǎn)回被攔截前路徑 或是 如果是直接訪問login則跳回主頁面
this.$router.push(this.$route.query.redirect || '/')
}
})
}
2.store.js 頁面
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
let store = new Vuex.Store({
state:{
accessToken:null
},
mutations:{
login_in(state, data){
state.accessToken = data
sessionStorage.setItem("accessToken", data)
},
login_out(state){
state.accessToken = null
sessionStorage.removeItem("accessToken")
}
}
})
export default store
3.index.js頁面
router.beforeEach((to,from,next)=>{
// isRequireAuthTrue
// 是否已經(jīng)登陸汤纸,驗證身份
if(sessionStorage.getItem("accessToken")){
next() // 程序正常繼續(xù)運行
}else{
if(to.path == "/login"){
next() // 程序正常繼續(xù)運行
}else{
next({
path:"/login", // 跳轉(zhuǎn)到login頁面
query:{redirect: to.path} // 記錄要進入的目標(biāo)地址
})
}
}
})
copy:
router.beforeEach((to,from,next)=>{})
當(dāng)一個導(dǎo)航觸發(fā)時粪摘,全局前置守衛(wèi)按照創(chuàng)建順序調(diào)用。守衛(wèi)是異步解析執(zhí)行维苔,此時導(dǎo)航在所有守衛(wèi) resolve 完之前一直處于 等待中碰辅。
每個守衛(wèi)方法接收三個參數(shù):
to: Route
: 即將要進入的目標(biāo) 路由對象 屬性:path params query hash fullPath name metafrom: Route
: 當(dāng)前導(dǎo)航正要離開的路由-
next: Function
: 一定要調(diào)用該方法來 resolve 這個鉤子懂昂。執(zhí)行效果依賴next
方法的調(diào)用參數(shù)。next()
: 進行管道中的下一個鉤子没宾。如果全部鉤子執(zhí)行完了凌彬,則導(dǎo)航的狀態(tài)就是 confirmed (確認的)。next(false)
: 中斷當(dāng)前的導(dǎo)航循衰。如果瀏覽器的 URL 改變了(可能是用戶手動或者瀏覽器后退按鈕)铲敛,那么 URL 地址會重置到from
路由對應(yīng)的地址。next('/')
或者next({ path: '/' })
: 跳轉(zhuǎn)到一個不同的地址会钝。當(dāng)前的導(dǎo)航被中斷伐蒋,然后進行一個新的導(dǎo)航。next(error)
: (2.4.0+) 如果傳入next
的參數(shù)是一個Error
實例迁酸,則導(dǎo)航會被終止且該錯誤會被傳遞給router.onError()
注冊過的回調(diào)先鱼。
確保要調(diào)用 next 方法,否則鉤子就不會被 resolved奸鬓。