一礁凡、vuex
一般的高氮,用戶登錄后會(huì)在本地持久化存儲(chǔ)用戶的認(rèn)證信息,本文以JWT的token為例顷牌。將用戶的token持久化到localStorage里剪芍,而用戶信息則存在內(nèi)存(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;
}
},
});
二韧掩、登錄成功時(shí)將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 } //登錄成功后跳入瀏覽的當(dāng)前頁面
});
}
}
return Promise.reject(error.response.data);
}
);
四、router.js權(quán)限路由配置
某些頁面規(guī)定必須登錄后才能查看 疗锐,可以再router中配置meta坊谁,將需要登錄的requireAuth設(shè)為true,
{
path: "/",
name: "home",
component: () => import("./views/Home.vue"),
meta: {
requireAuth: true,
}
},
{
path: "/login",
name: "login",
component: () => import("./views/login/login.vue"),
},
然后設(shè)置路由守衛(wèi)滑臊,在進(jìn)頁面之前口芍,判斷有token,才進(jìn)入頁面雇卷,否則返回登錄頁面鬓椭。
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();
}
});