vuex组件 vuex-persistedstate

vuex可以进行全局的状态管理,但刷新后刷新后数据会消失,这是我们不愿意看到的。怎么解决呢,我们可以结合本地存储做到数据状态持久化,但是太麻烦每次都要操作,所以此时就可以利用vuex-persistedstate插件

安装

npm install vuex-persistedstate --save

1.使用vuex-persistedstate默认存储到localStorage

 引入及配置:在store下的index.js

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

 

2.使用vuex-persistedstate存储到sessionStorage

 引入及配置:在store下的index.js

import createPersistedState from "vuex-persistedstate"
const store = new Vuex.Store({
   state: {},
   mutations: {},
   actions: {},
   plugins: [createPersistedState({
       storage:window.sessionStorage  // 同localStorage相同,只是将vuex的所有值存储到sessionStorage中
   })]
})

 

3.使用vuex-persistedstate指定需要持久化的state

 引入及配置:在store下的index.js

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

下边附上当前测试写的小demo,通过vuex控制组件中的加减运算

import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'  // 用于vuex状态管理与本地存储同步

Vue.use(Vuex)

const Store = new Vuex.Store({
  state: {
    count: 0,
    computedCount: 0,
    bb: 'bb'
  },
  mutations: {
    add(state, n = 1) {
      state.count += n
    },
    sub(state, n = 1) {
      state.count -= n
    }
  },
  actions: {
    addSync(context, n) {
      setTimeout(function () {
        context.commit('add', n)
      }, 1000);
    },
    subAsync(context, n) {
      setTimeout(() => {
        context.commit('sub', n)
      }, 1000)
    }
  },
  getters: {
    comp(state) {
      return `当前的count为${state.count + 1}`
    }
  },
  plugins: [
    createPersistedState({
      // 当state中的值发生变化的时候出发reduce函数
      reducer(val)  {
        console.log(val)  // value值为当前state中的所有值对象
        // return什么,localstorage中的key值为vuex的value值就是什么,而且是实时与state中的值保持同步
        return {
            count: val.count || 0,
            computedCount: val.computedCount,
            aa: 1
        }
    }
    })
  ]
})

export default Store
posted @ 2022-04-28 14:46  ~逍遥★星辰~  阅读(1885)  评论(0编辑  收藏  举报