vue router.beforeEach(),詳解
https://blog.csdn.net/heshuaicsdn/article/details/88020796
router.beforeEach()一般用來做一些進入頁面的限制。比如沒有登錄,就不能進入某些頁面,只有登錄了之後纔有權限查看某些頁面。。。說白了就是路由攔截。
1、Vue.beforeEach(function(to,form,next){}) /*在跳轉之前執行*/
2.Vue.afterEach(function(to,form))/*在跳轉之後判斷*/
第一步 規定進入路由需不需要權限
@/router/index.js
import A from '@/components/a'
{
path: '/a',
name: 'a',
component: A,
meta : { //加一個自定義obj
requireAuth:true //這個參數 true 代表需要登錄才能進入A
}
},
第二步 使用vuex整一個userId
@/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()
@/main.js
思路:【
如果(即將進入的這個路由需要權限才能進入){
如果(能獲取到這個老哥的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()
}
})
第四步
第三步這個/b路由其實就是登陸頁面,
當進入A頁面之前,需要請求接口,獲取一下是否有登陸過,然後把這個userId存在vuex的state裏。
當沒有userId時,則在登陸之後,存一個userId到state裏。然後就敲完收工