后台管理有不同角色,那么就有不同的权限
登录拦截,判断是否登录
router.beforeEach((to, from, next) => {
if (to.path === "/login") {
next();
} else {
const token = sessionStorage.getItem("token");
if (!token) {
next("/login");
} else {
next();
}
}
});
通过登录接口,获取用户的权限
通过接口,获取到权限列表后,放到store里和route的meta里`
login() {
this.$refs.loginFormRef.validate(async valid => {
if (!valid) return
const { data: res } = await this.$http.post('login', this.loginForm)
if (res.meta.status !== 200) return this.$message.error('登录失败!')
this.$store.commit('setRightList', res.rights)
this.$store.commit('setUsername', res.data.username)
sessionStorage.setItem('token', res.data.token)
initDynamicRoutes()
this.$message.success('登录成功')
this.$router.push('/home')
})
}
export function initDynamicRoutes() {
const currentRoutes = router.options.routes
const rightList = store.state.rightList
rightList.forEach(item => {
item.children.forEach(item => {
const itemRule = ruleMapping[item.path]
itemRule.meta = item.rights
currentRoutes[2].children.push(itemRule)
})
})
console.log(currentRoutes)
router.addRoutes(currentRoutes)
}
通过返回数据,渲染菜单
通过自定义指令控制是否显示和隐藏,是否禁用
import Vue from 'vue'
import router from '@/router.js'
Vue.directive('permission', {
inserted: function(el, binding) {
const action = binding.value.operation
const currentRight = router.currentRoute.meta
if (currentRight) {
if (currentRight.indexOf(action) === -1) {
// 不具备权限
const type = binding.value.effect
if (type === 'disabled') {
el.disabled = true//禁用
el.classList.add('is-disabled')
} else {
el.parentNode.removeChild(el)//删除
}
}
}
}
})
请求拦截,再次查看是否有权限
axios.interceptors.request.use(function(req) {
const currentUrl = req.url
if (currentUrl !== 'login') {
req.headers.Authorization = sessionStorage.getItem('token')
// 当前模块中具备的权限
const method = req.method
// 根据请求, 得到是哪种操作
const action = actionMapping[method]
// 判断action是否存在当前路由的权限中
const rights = router.currentRoute.meta
if (rights && rights.indexOf(action) === -1) {
// 没有权限
alert('没有权限')
return Promise.reject(new Error('没有权限'))
}
}
return req
})