addRoutes动态添加路由
router路由index.js
基本路由(不受权限控制的)
export const routes = [
{
path: "/login",
component: ()=>import('../views/login/index.vue'),
meta:{title:'登陆页'}
},
];
权限路由
export const perRouter = [
{
path: "/",
component: Layout,
redirect:'/advert',
roles:[],
children:[
{
path: "/advert",
component:()=>import('@/views/advert/advert.vue'),
meta:{title:'广告管理',icon:'el-icon-c-scale-to-original'},
roles:['select:advert'],
},
]
}
]
const router = new VueRouter({
mode: "hash",
base: process.env.BASE_URL,
routes:routes,
});
export default router;
1.登陆成功后调用权限接口获取当前账号的权限,addRoutes添加路由
getPermossion().then(res=>{
localStorage.setItem('permission',JSON.stringify(res.result.list)) //存储权限
let myRou = Permiss(res.result.list,perRouter,this.$router) //调用公共方法,判断权限,addRoutes(最新的路由)
this.$router.push("/advert");
})
Permiss公共方法中要把menu菜单渲染的数据存到vuex中,因为router路由不是响应式数据,没有观察和订阅,菜单就不会更新,
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{
menu:[]
},
getters:{
menu:state=>state.menu
},
mutations:{
menuChange:(state,data)=>{
state.menu = data
}
}
})
菜单组件:
computed:{
getMenu(){
if(this.$store.state.menu){
return this.$store.state.menu[0].children
}
}
},
2.刷新页面的时候再次调用公共方法,获取最新权限路由,app.vue中的create函数或者路由中调用(因为刷新页面的时候路由会重新实例化,之前添加的没有了)
let promissList = JSON.parse(localStorage.getItem('permission'))
if(localStorage.getItem('permission')){
Permiss(promissList,perRouter,router)
}
3.退出登录的时候要清除addRoutes添加的路由(location.reload()或者网上的跟换router.matcher方法)
遇到问题:登录的时候把判断后的路由存到了本地,刷新的时候取路由,页面依旧空白,路由不能存到本地,组件会被转换成字符串