vuex存储用户登录信息
前提是已经
npm install vuex --save
可以在新项目中建立一个文件夹,例如 store,包含store.js
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6a403c2fb6263b98c03bb4beb8807e16.png)
在这里以存储用户信息为例:
store.js中
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
name: JSON.parse(localStorage.getItem("userInfo")) || {}
},
getters: {
userName: state => {
return state.name;
}
},
mutations: {
getUserName(state, data) {
localStorage.setItem("userInfo", JSON.stringify(data));
state.name = data;
}
},
actions: {
getUserName({ commit }, data) {
commit("getUserName", data);
}
}
});
登录时login.vue
在退出登录的时候设置为空this.getUserName("");
例如使用这个信息userName
computed: { ...mapState({ userName: state => state.name }) },
在页面刷新vuex数据丢失的时候
在app.vue中加入
if (sessionStorage.getItem("store")) {
this.$store.replaceState(
Object.assign(
{},
this.$store.state,
JSON.parse(sessionStorage.getItem("store"))
)
);
}
window.addEventListener("beforeunload", () => {
sessionStorage.setItem("store", JSON.stringify(this.$store.state));
});