vuex store index.js配置登录
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
// 初始化时用sessionStore.getItem('token'),这样子刷新页面就无需重新登录
const state = {
user: window.sessionStorage.getItem('user'),
token: window.sessionStorage.getItem('token'),
btns:window.sessionStorage.getItem('btns'),
identity: window.sessionStorage.getItem('identity')
};
const mutations = {
//将token保存到sessionStorage里,token表示登陆状态
SET_TOKEN: (state, data) => {
state.token = data;
window.sessionStorage.setItem('token', data);
},
//获取用户名
GET_USER: (state, data) => {
// 把用户名存起来
state.user = data;
window.sessionStorage.setItem('user', data);
},
BTNS: (state, data) => {
state.btns = data;
window.sessionStorage.setItem('btns', data);
},
//登出
LOGOUT: state => {
// 登出的时候要清除token
state.token = null;
state.user = null;
window.sessionStorage.removeItem('token');
window.sessionStorage.removeItem('user');
},
//获取用户名
IDEN: (state, data) => {
// 把用户名存起来
state.identity = data;
window.sessionStorage.setItem('identity', data);
},
};
const actions = {};
export default new Vuex.Store({
state,
mutations,
actions,
});
// router index.js登录拦截
// 注册全局钩子用来拦截导航
router.beforeEach((to, from, next) => {
const token = store.state.token
if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
if (token) { // 通过vuex state获取当前的token是否存在
next()
} else {
console.log('该页面需要登陆')
next({
path: '/login'
// query: {redirect: to.fullPath} // 将跳转的路由path作为参数,登录成功后跳转到该路由
})
}
} else {
next()
}
})
export default router
本文来自博客园,作者:叶子玉,转载请注明原文链接:https://www.cnblogs.com/knuzy/p/11374584.html