官网也给出来了建议,把权限放在vuex里面,通过角色来访问。
在实际的使用过程中,我们的数据是从后台获取的,用户在登录的时候,根据用户的角色,动态获取了权限,前端在格式化路由进行展示。
实现思路就是从后台根据用户查询用户所分配的所有按钮权限 每一个按钮都有标识,然后前端来控制,我们先来看看表的设计:
1.接口获取数据转换成一个 可以直接读取的路由表:
const actions = {
generateRoutes({ commit, dispatch }, { asyncRoutes, routesMap }) {
const loadMenuData = []
let formatRoutes = []
Object.assign(loadMenuData, JSON.parse(asyncRoutes))
const tempAsyncRoutes = Object.assign([], [])
// 格式化路由
formatRoutes = formatResource()
const asyncFormatRoutes = formatRoutes
const routesFormatMap = asyncFormatRoutes
return new Promise(resolve => {
const filterRoutesMap = MultidimensionalToOnedimensional(routesFormatMap)
const accessedRoutes = filterAsyncRoutes(asyncFormatRoutes, filterRoutesMap)
commit('SET_ROUTES', accessedRoutes)
// 设置全部路由地址
const routerPaths = setRouterPath(store.getters.routes)
commit('setRouterPath', routerPaths)
resolve(accessedRoutes)
})
},
resetState({ commit }) {
return new Promise(resolve => {
commit('RESET_STATE')
resolve()
})
}
}
其中setRouterPath就是转换的方法,代码如下:是的
/**
* 把全部路由包含子路由地址存起来
* @param routerPath
* return paths
*/
export function setRouterPath(routerPath, paths = []) {
for (const item of routerPath) {
if (item.path && item.path !== 'null') {
paths.push(item.path)
}
if (item.children && item.children.length) {
setRouterPath(item.children, paths)
}
}
return paths
}
2.接下来我们在页面里面写个方法控制按钮:
模板页面代码如下:
。。。。。。。。。。省略
<!-- 操作按钮 -->
<div class="filter-container">
<el-button v-show="authorityList.userAdd.show" type="primary" icon="el-icon-plus" @click="handleAdd()">
{{ 添加 }}
</el-button>
<el-button v-show="authorityList.userEdit.show" type="primary" icon="el-icon-plus" @click="handleEdit()">
{{ 编辑}}
</el-button>
<el-button v-show="authorityList.userDel.show" type="primary" icon="el-icon-plus" @click="handleDel()">
{{ 删除}}
</el-button>
</div>
。。。。。。。。。。省略
在data里面定义当前页面所有的按钮:
authorityList: {
userAdd: { path: 'app/user/add', show: false },
userEdit: { path: 'app/user/edit', show: false },
userDel: { path: 'app/user/del', show: false }
}
在mounted里面定义一个检查权限的方法:
mounted() {
this.checkAuthority()
},
methods中的方法如下:
checkAuthority() {
for (const key in this.authorityList) {
this.authorityList[key].show = lookRouterPath(this.authorityList[key].path)
}
}
其中lookRouterPath的方法 就是检查路由地址的:
/**
* 检查页面按钮是否有权限
* @param path
* return boolean
*/
export function lookRouterPath(path) {
if (!path) return false
const routerPaths = read(ROUTERPATHS)
if (!routerPaths) return false
const routerPathList = JSON.parse(routerPaths)
let isLook = false
routerPathList.forEach(function(item) {
if (item.indexOf(path) !== -1) {
isLook = true
}
})
return isLook
}
这样就完成了权限精确到页面来控制了,效果如下: