Vue:vuex状态数据持久化插件vuex-persistedstate

项目结构

# 项目结构
$ tree
.
├── package.json
├── main.js
├── App.vue
└── store
    ├── cookie-storage.js
    ├── index.js
    └── persistedstate.js
# 快速原型开发
$ vue serve

代码

依赖 package.json

{
  "dependencies": {
    "js-cookie": "^2.2.1",
    "vue": "^2.6.12",
    "vuex": "^3.6.2",
    "vuex-persistedstate": "^4.0.0-beta.3"
  }
}

程序入口 main.js

import Vue from "vue";
import App from "./App.vue";
import store from "./store";
const app = new Vue({
  el: "#app",
  store: store,
  render: (h) => h(App),
});
export default app;

组件 App.vue

<template>
  <div class="">
    <input
      type="text"
      v-model="name"
    >
  </div>
</template>
<script>
export default {
  name: '',
  computed: {
    name: {
      get() {
        // 取出数据
        return this.$store.getters.name;
      },
      set(val) {
        // 更新数据
        this.$store.dispatch('setName', val);
      },
    },
  },
};
</script>
<style lang="scss" scoped>
</style>

Vuex组件入口 store/index.js

import persistedState from "./persistedstate";
import Vuex from "vuex";
import Vue from "vue";
Vue.use(Vuex);
const store = new Vuex.Store({
  // 数据状态
  state: { name: "" },
  // 获取 getter
  getters: {
    name: (state) => {
      console.log("getters.name");
      return state.name;
    },
  },
  // 同步 setter
  mutations: {
    setName(state, name) {
      console.log("mutations.setName");
      state.name = name;
    },
  },
  // 异步 setter
  actions: {
    setName({ commit }, name) {
      console.log("actions.setName");
      commit("setName", name);
    },
  },
  // 持久化插件
  plugins: [persistedState],
});
export default store;

持久化插件 store/persistedstate.js

import createPersistedState from "vuex-persistedstate";
import CookieStorage from "./cookie-storage.js";
const persistedState = createPersistedState({
  // 默认存储到localStorage
  //   storage: window.localStorage
  // 存储到cookie
  storage: CookieStorage,
});
export default persistedState;

定义持久化存储 store/cookie-storage.js

import Cookies from "js-cookie";
const CookieStorage = {
  getItem: (key) => Cookies.get(key),
  setItem: (key, value) => Cookies.set(key, value, { expires: 7 }),
  removeItem: (key) => Cookies.remove(key),
};
export default CookieStorage;