npm install vuex
在项目scr目录下新建store文件夹,在store文件夹下新建index.js文件。
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const state={
accountInfo:{
}
}
const mutations={
initUser(state,payload){
state.accountInfo=Object.assign(state.accountInfo,payload);
localStorage.setItem('accountInfo',JSON.stringify(state.accountInfo));
},
clear(state){
state.accountInfo={
}
}
}
//防止页面刷新vuex中的数据丢失
for(var item in state){
localStorage.getItem(item)?state[item] = JSON.parse(localStorage.getItem(item)): false;
}
export default new Vuex.Store({
state,
mutations
})
本文介绍了如何使用Vuex进行状态管理,包括安装Vuex、创建store文件夹与index.js文件的具体步骤。文中还详细展示了state、mutations的定义及localStorage与Vuex结合使用的方法,以实现数据持久化。
991

被折叠的 条评论
为什么被折叠?



