npm安装vuex及防止页面刷新数据丢失

本文介绍了如何使用Vuex进行状态管理,包括安装Vuex、创建store文件夹与index.js文件的具体步骤。文中还详细展示了state、mutations的定义及localStorage与Vuex结合使用的方法,以实现数据持久化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
})

  

转载于:https://www.cnblogs.com/luyuefeng/p/8334472.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值