
一:数据丢失的缘故起因
- vuex存储的数据只是在页面中,相称于全局变量,页面刷新的时间vuex里的数据会重新初始化,导致数据丢失。
- 由于vuex里的数据是保存在运行内存中的,当页面刷新时,页面会重新加载vue实例,vuex内里的数据就会被重新赋值。
二:办理的思路
- 将vuex中的数据直接保存到欣赏器缓存中(sessionStorage、localStorage、cookie)
- 页面刷新后再从欣赏器中取出
三:办理方法
方法一:
- 直接在vuex修改数据方法中将数据存储到欣赏器本地存储中
- import Vue from 'vue';
- import Vuex from 'vuex';
-
- Vue.use(Vuex);
-
- export default new Vuex.Store({
- state: {
- orderList: [],
- menuList: []
- },
- mutations: {
- orderList(s, d) {
- s.orderList= d;
- window.localStorage.setItem("list",jsON.stringify(s.orderList))
- },
- menuList(s, d) {
- s.menuList = d;
- window.localStorage.setItem("list",jsON.stringify(s.menuList))
- },
- }
- })
复制代码- if (window.localStorage.getItem("list") ) {
- this.$store.replaceState(Object.assign({},
- this.$store.state,JSON.parse(window.localStorage.getItem("list"))))
- }
复制代码 在此可以举行优化
- 通过监听beforeunload事故来举行数据的localStorage存储,beforeunload事故在页面刷新时举行触发,具体做法是在App.vue的created()周期函数中下如下代码:
- if (window.localStorage.getItem("list") ) {
- this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(window.localStorage.getItem("list"))))
- }
-
- window.addEventListener("beforeunload",()=>{
- window.localStorage.setItem("list",JSON.stringify(this.$store.state))
- })
复制代码 方法二:
npm install --save vuex-persistedstate
- 在store文件夹下的indedx.js中设置信息
- 使用vuex-persistedstate默认存储到localStorage
- import createPersistedState from "vuex-persistedstate"
- const store =newVuex.Store({
- state: {
- count: 1
- },
- mutations: {},
- actions: {},
- // 当state中的值发生改变,此时localStorage中的vuex的值会同步把state中的所有值存储起来,当页面刷
- 新的时候,state的值会从localStorage自动获取vuex的value值,赋值到state中
- plugins: [createPersistedState()]
- })
复制代码
- 使用vuex-persistedstate存储到sessionStorage
- import createPersistedState from "vuex-persistedstate"
- const store = new Vuex.Store({
- state: {},
- mutations: {},
- actions: {},
- plugins: [createPersistedState({
- storage:window.sessionStorage // 同localStorage相同,只是将vuex的所有值存储到sessionStorage中
- })]
- })
复制代码
- 使用vuex-persistedstate指定必要持久化的state
- import createPersistedState from "vuex-persistedstate"
- const store = newVuex.Store({
- state: {
- count: 0
- },
- mutations: {},
- actions: {},
- plugins: [createPersistedState({
- storage:window.sessionStorage,
- reducer(val) {
- // 此时,当count发生改变的时候,就会调用此函数,并且val的值为当前state对象,return的值为当前本地存储的value值(本地存储的key值为vuex)
- return {
- count: val.count,
- changeCount: 'aaa'
- }
- }
- })]
- })
复制代码 四:总结
- 其实办理此问题的方法有许多,根本上都是要借助于localStorage大概sessionStroage来存放。
来源:https://blog.csdn.net/qq_51441159/article/details/128047610
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |