Vuex持久化插件(vuex-persistedstate)**解决刷新数据消失的问题😊**

401 阅读1分钟

1.为什么使用持久化

目的: 让在vuex中管理的状态数据同时储存在本地。可免去自己储存的环节。

  • 在开发的过程中,像用户信息(名字,头像,token)需要vuex中储存且需要本地储存
  • 再例如,购物车如果需要未登录状态下也支持,如果管理在vuex中页面需要储存在本地

2.下载安装

yarn add vuex-persistedstate
//or
npm install --save vuex-persistedstate

3.使用

import Vuex from "vuex";
// 引入插件
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 };
            }
        })
    ]
});
​

4.注意

  • 默认是存储在localStorage中
  • key是存储数据的键名
  • 修改state后触发才可以看到本地存储数据的的变化