在默认模式下,vuex中保存的东西会在刷新之后被清空,导致我们想用vuex存储一些内容,刷新后无法获取。
可以利用持久性的存储比如localStorage或setStorageSync在app.vue监听刷新事件进行存储,app.vue加载时获取缓存,设置延迟清空存储,避免内存泄露。

1.纯vue非uni-app

利用localStorage的持久性存储结合vuex,
在app.vue的created

//在页面刷新时将vuex里的信息保存到localStorage里
window.addEventListener("beforeunload", () => {
  localStorage.setItem("userComMsg", JSON.stringify(this.$store.state));
});

//在页面加载时读取localStorage里的状态信息
if (localStorage.getItem("userComMsg")) {
  Object.assign(
    this.$store.state,
    JSON.parse(localStorage.getItem("userComMsg"))
  );
  //使用后清除内存
  setTimeout(function () {
    localStorage.removeItem("userComMsg");
  }, 300);
}

2.uni-app

以下方法h5可使用,但是小程序和app不完全确定可用。利用uni.setStorageSync来设置存储

在app.vue的onLaunch

//在页面刷新时将vuex里的信息保存到Storage里
window.addEventListener("beforeunload", () => {
	uni.setStorageSync("userComMsg", JSON.stringify(this.$store.state));
});

//在页面加载时读取Storage里的状态信息
if (uni.getStorageSync("userComMsg")) {
	Object.assign(
		this.$store.state,
		JSON.parse(uni.getStorageSync("userComMsg"))
	);
	//使用后清除内存
	setTimeout(function () {
		uni.removeStorageSync("userComMsg");
	}, 300);
}

这篇仅仅是个人记录,我只用在h5。app和小程序基本只用于测试。
有用就用,没用就全是你对。
你有素质我们就可以探讨,没有素质就不要杠。
不想浪费时间和别人杠。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐