1、检查该路由下, 所有的二级路由是否添加和格式规范。暂未发现问题
export const asyncRoutes=[
// 商品管理
{
path:'/product',
component:Layout,
name:'Product', // 一级路由的名字
meta:{title:'商品管理',icon:'el-icon-goods'},
children:[
{
path:'tradeMark',
name:'TradeMark',
component:()=>import('@/views/product/tradeMark'),
meta:{title:'品牌管理'}
},
{
path:'attr',
name:'Attr',
component:()=>import('@/views/product/Attr'),
meta:{title:'平台属性管理'}
},
{
path:'spu',
name:'Spu',
component:()=>import('@/views/product/Spu'),
meta:{title:'Spu管理'}
},
{
path:'sku',
name:'Sku',
component:()=>import('@/views/product/Sku'),
meta:{title:'Sku管理'}
}
]
},
2、接着查看显示该一级菜单的组件页面:该一级路由菜单和4个子路由是被遍历展示的
3、该routes计算结果,返回的是user仓库里的resultAllRoutes数据
computed: {
...mapGetters([
'sidebar'
]),
//返回user仓库的路由数据
routes() {
return this.$store.state.user.resultAllRoutes;
},
}
4、找到user仓库里的resultAllRoutes,数据从这里进行倒推
// 返回的结果也是一个state
const getDefaultState = () => {
return {
token: getToken(),
name: '',
avatar: '',
// 服务器返回的菜单信息(根据不同的角色,返回的标记信息,数组里面的元素是字符串)
routes: [],
buttons: [],
roles: [],
// 服务器返回的标记信息进行对比,最终需要展示的路由
resultAsyncRoutes: [],
// 最终需要对用户展示的全部路由
resultAllRoutes: []
}
};
5、该 resultAllRoutes 值是被mutations里的SET_RESULTASYNCROUTES方法计算后,添加存储的。
6、 user仓库内部,定义了一个computedAsyncRoutes方法,作用是:对比得出当前用户需要看见的路由
const computedAsyncRoutes = (asyncRoutes, routes) => {
console.log('routes',routes);
// 过滤当前用户需要展示的异步路由
return asyncRoutes.filter(item => {
if (routes.indexOf(item.name) != -1) {
// 递归
if (item.children && item.children.length) {
item.children = computedAsyncRoutes(item.children, routes);
}
return true
}
})
}
7、actions里的getInfo方法,调用computedAsyncRoutes方法,将项目本地的异步路由与服务器返回的异步路由进行对比,得到一个新的数组,提交给mutations
const actions = {
// 获取用户信息
getInfo({ commit, state }) {
return new Promise((resolve, reject) => {
getInfo(state.token).then(response => {
// 获取服务器返回的data数据
const { data } = response
if (!data) {
return reject('验证失败,请重新登录')
}
// 存储全部的用户信息
commit('SET_USERINFO', data)
// 内部将项目的异步路由与服务器返回的异步路由进行对比
commit('SET_RESULTASYNCROUTES', computedAsyncRoutes(cloneDeep(asyncRoutes), data.routes));
resolve(data)
}).catch(error => {
reject(error)
})
})
},
8、mutatios将数据存储进user仓库,并与任意路由合并,存储在state.resultAllRoutes里,给router添加新的子路由
const mutations = {
// 最终计算出来的异步路由
SET_RESULTASYNCROUTES: (state, resultAsyncRoutes) => {
// 保存当前用户的异步路由
state.resultAsyncRoutes = resultAsyncRoutes;
// 计算出当前用户需要展示的所有路由
state.resultAllRoutes = constantRoutes.concat(state.resultAsyncRoutes, anyRoutes);
// 给路由器添加新的路由
router.addRoutes(state.resultAllRoutes);
}
};
9、检查所有的运行逻辑后,回到computedAsyncRoutes方法里,由于对数据过滤的条件,是通过路由的name字段进行筛选。若服务器返回的权限码里包含了本地路由的name,则是可以展示的。
10、测试查看服务器返回的权限码:
可以看到服务器返回的权限码中,有Trademark字段,而本地书写的name是TradeMark,这里改掉就可以正常显示了。