一、vuex
一般的,用户登录后会在本地持久化存储用户的认证信息,本文以JWT的token为例。将用户的token持久化到localStorage里,而用户信息则存在内存(store)中。
state: {
token: "",
userName: ""
},
mutations: {
set_token(state, token) {
state.token = "JWT " + token;
localStorage.setItem("token", token);
},
del_token(state) {
state.token = "";
localStorage.removeItem("token");
},
setUserInfo(state, userName) {
state.userName = userName;
}
},
});
二、登录成功时将token持久化到localStorage
this.$axios
.post("/api/users/login", this.form)
.then(res => {
res = res.data;
if (res.code == 0) {
this.isLogin = true;
this.$store.commit("set_token", res.data.token);
this.$store.commit("setUserInfo", res.data.username);
if (this.$store.state.token) {
this.$router.push("/");
} else {
this.$router.replace("/login");
}
}
三、main.js中的axios
axios.interceptors.request.use(
config => {
//在所有请求头部添加token值
const token = store.state.token;
if (token) {
config.headers.Authorization = token;
}
return config;
},
error => {
console.log("err");
return Promise.reject(error);
}
);
// response 拦截器
axios.interceptors.response.use(
response => {
return response;
},
error => {
if (error.response) {
switch (error.response.status) {
case 401:
this.$store.commit("del_token");
router.replace({
path: "/login",
query: { redirect: router.currentRoute.fullPath } //登录成功后跳入浏览的当前页面
});
}
}
return Promise.reject(error.response.data);
}
);
四、router.js权限路由配置
某些页面规定必须登录后才能查看 ,可以再router中配置meta,将需要登录的requireAuth设为true,
{
path: "/",
name: "home",
component: () => import("./views/Home.vue"),
meta: {
requireAuth: true,
}
},
{
path: "/login",
name: "login",
component: () => import("./views/login/login.vue"),
},
然后设置路由守卫,在进页面之前,判断有token,才进入页面,否则返回登录页面。
if (localStorage.getItem("token")) {
store.commit("set_token", localStorage.getItem("token"));
}
router.beforeEach((to, from, next) => {
if (to.matched.some(r => r.meta.requireAuth)) {
if (store.state.token) {
next();
} else {
next({
path: "/login"
});
}
} else {
next();
}
});