vue.js - Vue CLI 更新 cookie 还是更新存储?
问题描述
所以我正在用 Vue、Node 和 Vuex 制作一个项目。现在我将用户数据存储在 cookie 中,而不是 vuex 存储中。但是我遇到了一个问题,我需要实时更新用户数据,比如当他买东西时,我需要在网页上更新它的钱。鞠躬如何更改cookie中的值?有没有办法更新 cookie 或者我应该为此使用 vuex 存储?
解决方案
首选的方法是将状态保存在 vuex 中,并使用持久性插件来持久化 vuex 状态的部分(或全部)。
例如,您可以使用vuex-persist。它具有对,等
的内置支持。
要将您的状态保存到 cookie 中,您可以使用js-cookie:localStorage
sessionStorage
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]
});
推荐阅读
- c - Matlab Coder 生成的名为 i386 的变量
- python - Python: abstract property type validation
- apache-kafka - Mirrormaker2.0 vs 融合复制器
- python - How to add _ between group of digits in YAML using Python's PyYAML
- swift - 在 SwitfUI 中显示 UIImage 很暗 - Apple Watch
- azure-devops - How to download an image from Azure DevOps Services HTML Field using API
- javascript - 如何在 Shopify 中使用 UTM 活动值标记新订单
- swift - 将 .onReceive 闭包添加到 SwiftUI 列表 -> 奇怪的错误
- gensim - LdaMallet 中的主题建模
- python - 处理要预测的元组中的分类值