Vuex data persistence - vuex-persistedstate (to solve the problem of page refresh stroe data loss)

The data we store in vuex is only placed in the browser cache, and it will be lost when the page is refreshed.
Of course, it can also be stored locally through vuex, and then retrieved can also realize that the page refresh data will not be lost.
This article mainly explains the vuex-persistedstate plug-in, the principle is the same as above, except that there is no need to write the stored code by hand, it can be realized according to simple configuration

1. Download

npm install vuex-persistedstate --save

2. Use - import and configure plugins in index.js in the store folder

According to the requirements of the project, it can be configured by modules, or it can be configured without modules

1. Regardless of module

Just configure it directly in stroe/index.js在这里插入代码片

import Vuex from "vuex";
import Vue from 'vue'
// 引入插件
import createPersistedState from "vuex-persistedstate";
Vue.use(Vuex);

const state = {
    
    };
const mutations = {
    
    };
const actions = {
    
    };

const store = new Vuex.Store({
    
    
  state,
  mutations,
  actions,
  /* vuex数据持久化配置 */
  plugins: [
    createPersistedState({
    
    
      // 存储方式:localStorage、sessionStorage、cookies
      storage: window.sessionStorage,
      // 存储的 key 的key值
      key: "store",
      render(state) {
    
    
        // 要存储的数据:本项目采用es6扩展运算符的方式存储了state中所有的数据
        return {
    
    
          ...state
        };
      }
    })
  ]
});

export default store;

2. Sub-module

In the module write this:

export default ({
    
    
    state: {
    
    },
    mutations: {
    
    },
    actions: {
    
    }
})

The configuration in stroe/index.js is as follows:

import Vuex from "vuex";
import Vue from 'vue'
// 引入模块
import fanSystem from './modules/fanSystem'


// 引入插件
import createPersistedState from "vuex-persistedstate";
Vue.use(Vuex);

const getters = {
    
    }

const store = new Vuex.Store({
    
    
  // 有哪些模块
  modules: {
    
    
    fanSystem
  },
  getters,
  /* vuex数据持久化配置 */
  // plugins: [createPersistedState()],//没有任何参数的配置写法
  plugins: [
    createPersistedState({
    
     //带参数的写法
      // 存储方式:localStorage、sessionStorage、cookies
      storage: window.sessionStorage,
      // 存储的 key 的key值(如果不写默认是vuex)
      key: "store",
      paths: ['fanSystem', ] //要存的数据模块,如果不配置,默认所有模块的数据都保存
    })
  ]
});

export default store;

After the module is divided, we call the methods in mutations and actions unchanged.

this.$store.commit[方法名] // mutations
this.$store.dispath[方法名] // actions

When fetching the data in the state, it needs to be fetched by module

this.$store.state[模块名][数据名]

In this way, we have configured it, and we don’t need to write the storage method by ourselves.

Guess you like

Origin blog.csdn.net/pink_cz/article/details/126272569