1、登录成功后,后端返回的数据格式
{
"code": 100,
"msg": "登录成功",
"role": 1,
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNjQ2NzI3NDkzLCJlbWFpbCI6IiJ9.9cBPqkkTxXS2aAjwRadcWuQLc5wgHdAG_YeRc82hGz0",
"data": {
"username": "admin",
"icon": "/media/icon/avatar09.jpg/",
"get_position": "系统管理员",
"role": 1
},
"right": [
{
"id": 1,
"authName": "用户管理",
"icon": "el-icon-user-solid",
"children": [
{
"id": 1,
"authName": "创建用户",
"path": "createuser",
"right": "add",
"component": "createuser"
}
]
},
{
"id": 2,
"authName": "部门管理",
"icon": "el-icon-user-solid",
"children": [
{
"id": 2,
"authName": "创建部门",
"path": "createpart",
"right": "add",
"component": "createpart"
}
]
},
]
}
3、login组件登录成功后,
import {initRoutes} from '@/router'
// this.$cookies.set("oatoken", res.data.data.token, '7d')
sessionStorage.setItem('oatoken', res.data.token)
//调用store中的方法setRightList,后面是传递的数据
this.$store.commit('setRightList', res.data.right)
this.$store.commit('setUsername',res.data.data.username)
this.$store.commit('setIcon',res.data.data.icon)
this.$message({
message: '登录成功,欢迎。',
type: 'success'
})
//调用store中的index.js的方法,push路由
initRoutes()
4、initRoutes()方法的作用,动态添加路由
//创建一个函数,将用户权限对应的路由添加进来
export function initRoutes () {
//根据二级路由,将路由添加进来
console.log(router) //查看路由器结构
const currentRoutes = router.options.routes
//找到home下的children位置,将路由push进来
//用户的权限数据我们是保存到vuex中了,
const rightList=store.state.rightList
//遍历一级菜单
rightList.forEach(item=>{
//遍历二级菜单
item.children.forEach(item=>{
const temp = ruleMapping[item.path]
//给路由加上上元数据meta属性
temp.meta = item.right
currentRoutes[2].children.push(temp)
})
})
//将路由添加进来
router.addRoutes(currentRoutes)
}
5、在util文件夹下创建http.js文件
import axios from 'axios'
import Vue from 'vue'
import router from '@/router'
const actionMapping = {
'get': 'view',
'post': 'add',
'put': 'edit',
'delete': 'delete'
}
axios.interceptors.request.use((req)=>{
//vue获取当前所在路由(前端的路由)router.currentRoute
console.log(router.currentRoute.path)
console.log(router.currentRoute.meta)
//判断非权限范围内的请求,我们在路由规则的meta中存放了用户对于该路由的权限
//判断当前请求的行为:get、post、put、delete
const action = actionMapping[req.method]
const currentRight = [router.currentRoute.meta]
if(currentRight && currentRight.indexOf(action)===-1){
//没有权限
alert('没有权限')
return Promise.reject(new Error('没有权限'))
}
//返回req,才能进行请求继续
return req
})
//响应拦截器:当用户的token失效的时候,就跳转到登录界面
axios.interceptors.response.use((res) => {
if (res.data.code === 401) {
router.push('/login')
//清空token
sessionStorage.clear()
//清空vuex中数据,刷新页面
window.location.reload()
}
return res
})
Vue.prototype.$axios = axios
6、main.js引入