首页 > 解决方案 > Vue CLI 更新 cookie 还是更新存储?

问题描述

所以我正在用 Vue、Node 和 Vuex 制作一个项目。现在我将用户数据存储在 cookie 中,而不是 vuex 存储中。但是我遇到了一个问题,我需要实时更新用户数据,比如当他买东西时,我需要在网页上更新它的钱。鞠躬如何更改cookie中的值?有没有办法更新 cookie 或者我应该为此使用 vuex 存储?

标签: vue.jsvuex

解决方案


首选的方法是将状态保存在 vuex 中,并使用持久性插件来持久化 vuex 状态的部分(或全部)。

例如,您可以使用vuex-persist。它具有对,等
的内置支持。 要将您的状态保存到 cookie 中,您可以使用js-cookielocalStoragesessionStorage

import Vuex, { Store } from 'vuex';
import VuexPersistence from 'vuex-persist';
import Cookies from 'js-cookie';

const vuexCookie = new VuexPersistence({
  restoreState: (key, storage) => Cookies.getJSON(key),
  saveState: (key, state, storage) =>
    Cookies.set(key, state, {
      expires: 3
    }),
  modules: ['user'] // only save the user module state in the cookie
});

const store = new Store({
  modules: {
    user: {
      state: {name: "User 1"},
      // TODO: getters, mutations, etc...
    },
    // ... more modules
  },
  plugins: [vuexCookie.plugin]
});

(示例修改自vuex-persist详细示例

您可以为每个 vuex 模块指定自定义持久性策略,因此您可以为 vuex 状态的不同部分设置不同的持久性策略:

const vuexLocal = new VuexPersistence({
  storage: window.localStorage,
  reducer: (state) => ({ cache: state.cache }) //only save cache module
});
const vuexSession = new VuexPersistence({
  storage: window.sessionStorage,
  reducer: (state) => ({ user: state.user }) //only save user module
});

const store = new Vuex.Store({
  modules: {
    user: { /* ... */ }, // will be stored in sessionStorage
    cache: { /* ... */ }, // will be stored in localStorage
    foobar: { /* ... */ } // not persisted, will reset on page reload
  },
  plugins: [vuexLocal.plugin, vuexSession.plugin]
});

推荐阅读