做登录之前应该先确定那些页面需要进行登录验证,之后给相应的页面的路由添加路由元信息,如果需要验证的页面非常多,可以将元信息添加在父亲上
meta: {
isLogin: true
}
接下来进行导航守卫,代码如下(自己将代码单独提出来):
import store from '../store';
import router from './index';
router.beforeEach((to,from,next)=>{
//1.判断是否需要登录 matched
if (to.matched.length>0 && !to.matched.some(record => record.meta.isLogin)) {
next();//login 404
}else{
//需要登录---
//2.判断是否已经登录-- token数据
if(store.state.loginModule.userinfo.token){
next();
}else{
next('/login')
}
}
})
在此之前需要处理一下 token 数据,在 store 的 modules 中添加 loginModule,并在 store 中导入代码如下:
import api from '../../api';
import jwt from 'jwt-decode';
import router from '../../router';
import element from 'element-ui';
export default {
namespaced:true,
state:{
userinfo:{
user:'',
token:'',
isLogin:false,
}
},
mutations:{
setUser(state,params){
state.userinfo=params
}
},
actions:{
async getLoginActions({commit},params){
let res= await api.getLogin(params)
if (res.status === 200) {
let temp = {
user: jwt(res.data).username,
token: res.data,
isLogin: Boolean(res.data),
};
//存储vuex
commit('setUser',temp)
//存储本地
localStorage.setItem('userToken',JSON.stringify(temp))
//跳转
router.push('/')
} else {
//错误--弹框信息 element
console.log('错误');
//this.$message.error('错了哦,这是一条错误消息');
element.Message.error('错误')
}
}
}
}
在登录页的编写方法
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
let { username, password } = this.ruleForm;
if (this.activeName === "login") {
this.getLoginActions({
username,
password,
});
} else {//注册
this.$api.register({ username, password }).then((res) => {
console.log(res);
if (res.status === 200) {
this.$message({
message: "恭喜你,注册成功成为管理员,请点击登录",
type: "success",
});
} else {
}
});
}
} else {
console.log("error submit!!");
return false;
}
});
},
在访问接口的时候会出现跨域的情况,在vue.config.js 中配置如下代码:
module.exports = {
devServer: {
proxy: {
'/api': {//http://192.168.xx.xx/api/xx/ 后台接口:相对路径
target: 'http://localhost:5000',//目的地址路径 本地研发环境
changeOrigin: true,//允许跨域
pathRewrite: {//重定向
"^/api": ""
}
},
//....
}
}
}
解决完跨域后,记得重新启动服务
获取到token后需要解析Token,安装jwt依赖,并在登录页导入
npm i jwt-decode --save
user: jwt(res.data).username,
将获取到的数据存储在Vuex中
let temp = {
user: jwt(res.data).username,
token: res.data,
isLogin: Boolean(res.data),
};
//存储vuex
commit('setUser',temp)
接着将数据存储在本地,并跳转(对象转字符串)
//存储本地
localStorage.setItem('userToken',JSON.stringify(temp))
//跳转
router.push('/')
在另建个文件用于获取本地数据,并存储在vuex中(字符串转对象)
//获取本地数据
let user=localStorage.getItem('userToken')
if(user){
store.commit('loginModule/setUser',JSON.parse(user))
}
退出登录方法
//退出登录--
loginOut() {
//清空数据
this.setUser({
user:'',
token:'',
isLogin:false
});
localStorage.removeItem('userToken')
this.$router.push('/login')
},