我正在使用vuex进行状态管理 这是我的vuex代码,
我的逻辑是,如果令牌存储在本地存储中,则它将isAuthenticated设置为true,这样可以很容易地检查路由。但是有些路由不起作用。
import axios from "axios";
import router from "../../router";
const state = {
token: localStorage.getItem("tkn") || "",
isAuth: false,
};
const getters = {
isAuthenticated: (state) => !!state.token,
authStatus: (state) => state.isAuth,
};
const actions = {
login({ commit }, loginData) {
// commit('auth_request')
axios
.post("/api/adminuser/auth/login", loginData)
.then((resp) => {
console.log(resp);
localStorage.setItem("tkn", resp.data.token);
axios.defaults.headers.common["Authorization"] = resp.data.token;
commit("setToken", resp.data.token);
router.push("/");
})
.catch((err) => {
console.log(err);
commit("authError", err);
localStorage.removeItem("token");
});
},
};
const mutations = {
setToken: (state, token) => ((state.token = token), (state.isAuth = true)),
authError: (state) => (state.isAuth = false),
};
export default {
state,
getters,
actions,
mutations,
};
这是我的路由器代码
import Vue from "vue";
import VueRouter from "vue-router";
import auth from "../store/modules/auth.js";
Vue.use(VueRouter);
const routes = [
{
path: "/signin",
name: "signin",
component: () => import("../components/Authentication/Signin.vue"),
},
{
path: "/",
name: "dashboard",
component: () => import("../components/Dashboard/Dashboard.vue"),
meta: {
requiresAuth: true,
},
},
];
const router = new VueRouter({
mode: "history",
routes,
});
router.beforeEach((to, from, next) => {
if (to.name !== "signin" && auth.getters.isAuthenticated == false)
next({ name: "signin" });
else next();
});
export default router;
当前,如果我仍然登录,我可以转到登录页面,甚至可以不经过身份验证就转到仪表板。
答案 0 :(得分:0)
使用之前,您应该先创建商店
// auth.js
import Vue from 'vue'
import Vuex from 'vuex'
import router from "../../router";
Vue.use(Vuex)
// ....
export default new Vuex.Store({
state,
getters,
actions,
mutations,
});
否则,auth.getters.isAuthenticated
将是函数,而不是vuex获取器。
vuex指南在这里https://vuex.vuejs.org/guide/
答案 1 :(得分:0)
请创建如下所示的函数,在一个名为helper.js的文件中,然后在main.js中对其进行初始化
helper.js
import axios from 'axios';
export function initialize(store, router)
{ router.beforeEach((to,from,next)=>{
const requiresAuth= to.matched.some(record=>record.meta.requiresAuth)
const currentUser = store.state.isAuthenticated;
if(requiresAuth && !currentUser){ next('/signin');}
else if(to.path=='/signin' && currentUser){ next('/')}
else { next()}
})
}
在您的main.js中
import {initialize} from './helper';
import router from './router'
import store from './store'
initialize(store, router);
登录页面
methods: {
...mapActions(["login"]),
loginUser: function(event) {
event.preventDefault();
this.login({ email: this.email, password: this.password })
.then(()=>{ this.$router.replace({name:'dashboard'})
//forward to this path after login
}).catch(()=>{console.log('login fail') });
}
},