vue单页面应用刷新网页后vuex的state数据丢失

一、问题
vue 写的项目,用 vuex 来做全局的状态管理, 发现当刷新网页后,保存在 vuex 实例 store 里的数据会丢失。因为 store 里的数据是保存在运行内存中的,当页面刷新时,页面会重新加载 vue 实例,store 里面的数据就会被重新赋值。
二、解决思路
将 state 里的数据保存一份到本地存储localStorage、sessionStorage、cookie中。
三、解决步骤
1、使用 localStorage、sessionStorage、cookie
首先得选择合适的客户端存储。
localStorage是永久存储在本地,除非你主动去删除;
sessionStorage是存储到当前页面关闭为止;
cookie则根据你设置的有效时间来存储,但缺点是不能储存大数据且不易读取。
这里选择的是sessionStorage,选择的原因 vue 是单页面应用,操作都是在一个页面跳转路由,另一个原因是sessionStorage 可以保证打开页面时 sessionStorage 的数据为空,而如果是 localStorage 则会读取上一次打开页面的数据。
由于 state 里的数据是响应式,所以 sessionStorage 存储也要跟随变化。又由于 vuex 规定所有 state 里数据必须通过 mutation 方法来修改,所以就是 mutation 修改 state 的同时修改 sessionStorage 对应存储的属性。
代码如下:

const Storage = window.sessionStorage;

const createForm = {
	state: {
		create: Storage.getItem("createForm") ? JSON.parse(Storage.getItem("createForm")) : {}
	},
	mutations: {
		SET_CREATE: (state, params) => {
			state.create = params;
			Storage.setItem("createForm", JSON.stringify(params));
		},
		DELETE_CREATE: state => {
			state.create = {};
			Storage.removeItem("createForm");
		}
	}
}

export default createForm;

2、使用 vuex-persistedstate
使用方法:
第一步:安装

npm install vuex-persistedstate  --save

第二步:引入及配置,在 store 下的 index.js 中

import createPersistedState from "vuex-persistedstate";
const store = new Vuex.Store({
	// ...
	plugins: [createPersistedState()]
});

想要存储到 sessionStorage,配置如下:

import createPersistedState from "vuex-persistedstate";
const store = new Vuex.Store({
	// ...
	plugins: [createPersistedState({
		storage: window.sessionStorage
	})]
});

想使用 cookie 或 localStorage 同理。
vuex-persistedstate 默认持久化所有 state,指定需要持久化的 state,配置如下:

import createPersistedState from "vuex-persistedstate";
const store = new Vuex.Store({
	// ...
	plugins: [createPersistedState({
		storage: window.sessionStorage,
		reducer(val) {
			return {
				// 只储存 state 中的 user
				user: val.user
			}
		}
 	})]
  })
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值