本文我们主要来聊聊登录以及组件的动态加载。
登录状态保存
当用户登录成功之后,需要将当前用户的登录信息保存在本地,方便后面使用。具体实现如下:
登录成功保存数据
在登录操作执行成功之后,通过commit操作将数据提交到store中,核心代码如下:
this.postRequest('/login', {
username: this.loginForm.username,
password: this.loginForm.password
}).then(resp=> {
if (resp && resp.status == 200) {
var data = resp.data;
_this.$store.commit('login', data.msg);
var path = _this.$route.query.redirect;
_this.$router.replace({path: path == '/' || path == undefined ? '/home' : path});
}
});
store
store的核心代码如下:
export default new Vuex.Store({
state: {
user: {
name: window.localStorage.getItem('user' || '[]') == null ? '未登录' : JSON.parse(window.localStorage.getItem('user' || '[]')).name,
userface: window.localStorage.getItem('user' || '[]') == null ? '' : JSON.parse(window.localStorage.getItem('user' || '[]')).userface
}
},
mutations: {
login(state, user){
state.user = user;
window.localStorage.setItem('user', JSON.stringify(user));
},
logout(state){
window.localStorage.removeItem('user');
}
}
});
为了减少麻烦,用户登录成功后的数据将被保存在localStorage中(防止用户按F5刷新之后数据丢失),以字符串的形式存入,取的时候再转为json。当用户注销登陆时,将localStorage中的数据清除。
组件动态加载
在权限管理模块中,这算是前端的核心了。
核心思路
用户在登录成功之后,进入home主页之前,向服务端发送请求,要求获取当前的菜单信息和组件信息,服务端根据当前用户所具备的角色,以及角色所对应的资源,返回一个json字符串,格式如下:
[
{
"id": 2,
"path": "/home",
"component": "Home",
"name": "员工资料",
"iconCls": "fa fa-user-circle-o",
"children": [
{
"id": null,
"path": "/emp/basic",
"component": "EmpBasic",
"name": "基本资料",
"iconCls": null,
"children": [],
"meta": {
"keepAlive": false,
"requireAuth": true
}
},
{
"id": null,
"path": "/emp/adv",
"component": "EmpAdv",
"name": "高级资料",
"iconCls": null,
"children": [],
"meta": {
"keepAlive": false,
"requireAuth": true
}
}
],
"meta": {
"keepAlive": false,
"requireAuth": true
}
}
]
前端在拿到这个字符串之后,做两件事:1.将json动态添加到当前路由中;2.将数据保存到store中,然后各页面根据store中的数据来渲染菜单。
