此处用mockjs模拟
const menuList = [
{'id': 1, path:'/uploadSpec','authName': "上传spec", icon: 'User', children:[], rights:['view','add','edit','delete']},
{'id': 2, path:'/showSpec', 'authName': "Spec预览", icon: 'DataAnalysis',children:[], rights:['view','add','edit','delete']},
{'id': 3, path:'/generateTxt', 'authName': "生成测试数据", icon: 'DataAnalysis',children:[], rights:['view','add','edit','delete']},
{'id': 4, path:'/generateCronjob', 'authName': "生成转码程序", icon: 'Promotion',children:[], rights:['view','add','edit','delete']},
{'id': 5, path:'/pdfCompare', 'authName': "PDF文档对比", icon: 'DocumentCopy',children:[], rights:['view','add','edit','delete']},
{'id': 6, path:'/resourceUpdate', 'authName': "资源更新管理", icon: 'Management',children:[], rights:['view','add','edit','delete']},
{'id': 7, path:'/generateTestCase', 'authName': "自动生成ST/SIT案例", icon: 'Files',children:[], rights:['view','add','edit','delete']},
{'id': 8, path:'/userManagement', 'authName': "用户管理", icon: 'User', rights:['view']},
{'id': 9, path:'/roleManagement', 'authName': "角色管理", icon: 'Stamp', rights:['view']},
]
import * as api from '@/api/api'
import { ElMessage } from 'element-plus'
const state = () => {
return {
user:JSON.parse(sessionStorage.getItem("user") || '{}'),
menuList: JSON.parse(sessionStorage.getItem("menuList") || '[]'),
}
}
const getters = () => {}
const actions = {
// 注意async位置和箭头函数写法
login: async({ commit }, user) => {
// 调用登录接口
try {
let result = await api.login(user);
if (result.data.code === 200) {
sessionStorage.setItem("token", result.data.data.token);
// 调用获取user信息接口
let loginUser = await api.getLoginUser();
// 调用mutations的login方法
if (loginUser.data.code === 200) {
commit('login', loginUser.data.data);
} else {
ElMessage.error("登录失败:用户信息获取失败");
}
} else {
ElMessage.error("登录失败:" + result.data.errorMsg);
}
} catch (error) {
throw error;
}
},
register: async({ commit, state }, user) => {
// 调用注册接口,注册不需要更新vuex,所以不需要调用mutations
try {
let registerUser = await api.register(user);
if (registerUser) return registerUser;
} catch (error) {
throw error;
}
},
}
const mutations = {
initUser: (state) => {
// 从localStorage中获取数据设置进user中,否则通过刷新页面时,获取不到state中的user信息
state.user = JSON.parse(sessionStorage.getItem("loginUser"));
},
login: (state, user) => {
// 登录成功后将user信息存到state中,且缓存到localStorage中
state.user = user;
state.menuList = user.menuList;
sessionStorage.setItem("loginUser", JSON.stringify(user));
sessionStorage.setItem("menuList", JSON.stringify(user.menuList));
},
}
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
导航菜单
{{menu.authName}}
...
import { computed } from "vue";
import { useStore } from "vuex";
const store = useStore();
const menuList = computed(() => store.state.user.menuList);
...
就是菜单数据没有设置到本地sessionStorage中
sessionStorage.clear();