看了好多動態(tài)路由的方法看到頭暈,最后還是自己搞了個方法解決。
使用
- addRouter
- 本地存儲
- 路由鉤子
思路
router/index.js
- 在登錄驗證通過后,獲取權限通過不同權限掛載不同權限的路由。
路由處理
這兩個為動態(tài)追加的路由路徑
// 平臺路由
import platform from './0'
//運營路由
import management from './1'
正常的路由路勁
Vue.use(Router)
const router = new Router({
mode: 'hash',
routes:[
{
path: '/',
name: '/',
component: Login,
},
//......寫固定路由
過濾空路由
{
path:"*",
component:Login,
}
]
})
只加載一次的 上鎖
let off = true;
// 注冊全局鉤子用來攔截導航
router.beforeEach((to, from, next) => {
// 動態(tài)添加路由
if(off){
let routers = []
//這里為讀取本地的權限 測試里面只有0,1兩個權限
switch (window.sessionStorage.getItem('jurisdiction')) {
case "0":
routers = platform
break;
case "1":
routers = management
break;
default:
break;
}
router.addRoutes(routers)
//鎖住
off = false
}
})
被上面導入的路徑代碼如下
0.js || 1.js
//設置
const Setup = () => import('@/pages/setup/0/Setup.vue')
export default [
//首頁
{
path: '/index',
name: 'Index',
component: Index,
meta: { requiresAuth: true },
},
......
]
搞完這些后發(fā)現(xiàn)一個問題,不會加載,需要刷新頁面才會出現(xiàn)。當時想了好多原因,不想了直接用了一個蠢辦法,登陸成功后刷新一次
// 登陸
login (formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
this.$store.dispatch('toLogin', {
loginUser: this.ruleForm.username,
loginPassword: this.ruleForm.password
}).then(() => {
this.$router.go(0) //登陸成功后刷新一次再去獲取信息
this.$store.dispatch('getUser')
......
以下為超綱部分
這樣又出了一個問題,刷新后加載出來的頁面導航條第一個不會選中。默認進入第一個導航條不選中有點煩。查看數(shù)據(jù)發(fā)現(xiàn)已經(jīng)掛載了需要觸發(fā)一次點擊事件。然后發(fā)現(xiàn)貌似強制觸發(fā)事件也不行。最后靈機一動寫了個自定義指令。
在頁面掛載之前
<el-menu
:default-active="activeIndex"
background-color="transparent"
@select="handleSelect"
>
<el-menu-item
@click="routerGo(item[1])"
:key="item[1].index"
v-acti="item[1].index" //自定義指令
v-for="(item,index) in showEnd"
:index="item[1].index"
>
</el-menu-item>
</el-menu>
directives:{
'acti':{
bind(el, binding,vnode){
if(binding.value == 0 && window.sessionStorage.getItem('activeIndex') == null){
el.click()
return
}
if(window.sessionStorage.getItem('activeIndex') == binding.value){
el.click()
}
}
}
},
data(){
return {
//最終掛載的路徑
showEnd:null,
jurisdiction:'',
//默認點擊的值
activeIndex:"0",
}
},
methods: {
handleSelect(key, keyPath) {
window.sessionStorage.setItem('activeIndex',key)
},
// 切頁面
routerGo(item){
this.$router.push(item.path)
}
},
如果頁面初始存?zhèn)€點擊項感覺這里可以不用。畢竟初始只用第一個
created() {
if(null == window.sessionStorage.getItem('activeIndex')){
window.sessionStorage.setItem('activeIndex',this.activeIndex);
}
},
//加載不同的導航條
mounted() {
this.jurisdiction = window.sessionStorage.getItem('jurisdiction');
let that = this
switch (this.jurisdiction) {
case "0":
that.showEnd = that.showList1
break;
case "1":
that.showEnd = that.showList2
break;
}
},
//監(jiān)控路由跳轉跳轉讓該頁面的導航條處于激活狀態(tài)
watch: {
$route(to,from){
let path = "/"+(to.path.split("/")[1])
this.showEnd.map(item => {
if(item[1].path == path){
this.activeIndex = item[1].index
}
})
}
},