1.store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import qs from 'qs'
import example from './module-example'
import _ from 'lodash';
Vue.use(Vuex)
Vue.prototype.$qs = qs
/*
* If not building with SSR mode, you can
* directly export the Store instantiation
*/
export default function (/* { ssrContext } */) {
const Store = new Vuex.Store({
state: {
user: {},
token: "",
title: ''
},
modules: {
example
},
getters: {
user(state){
if (!_.size(state.user)) {
var user = {};
var u = JSON.parse(window.localStorage.getItem("user"));
if (u) {
user = u;
}
localStorage.setItem("user", JSON.stringify(user));
state.user = user; //this.$store.commit("setUser", user);
return user;
}
return state.user
},
token(state){
return state.token
}
},
mutations: {
setUser (state, user) {
var _user = _.merge({}, state.user);
if (!_.size(_user)) {
_user = {};
}
_.each(user, function (value, key) {
_user[key] = value;
})
sessionStorage.setItem("user", JSON.stringify(_user));
state.user = _user;
},
setToken (state, token) {
sessionStorage.setItem("token", token);
state.token = token;
},
LOGOUT (state){
sessionStorage.clear();
state.user = {};
state.token = null
},
}
})
return Store
}
设置 store 里面的user 和token 属性,并给添加getter和setf方法,为其赋值
为了方便退出直接加了一个Logout的方法直接清空 所有对象
2.在login.vue 里登录成功返回user和token后将user和token保存至store中,如下使用commit方法
当将登录对象保存至store后,用this.store.getters.token()来获取token对象,
或者 token = window.sessionStorage.getItem('token') 获取
3.退出
再需要退出的页面写一个退出登录的方法,调用store里面的logout方法,直接清空store中存储对象,再跳转至登录页面
关注
如果有问题,请在下方评论
想获得更多的学习知识请关注微信公众号:西北码农或扫下方二维码