vuex刷新状态重置问题
文章类型:Vue
发布者:admin
发布时间:2023-05-17
Vuex中,当页面刷新时,Vuex的状态会被重置为其初始值。这是因为Vuex的状态存储在内存中,而不是持久化到浏览器的本地存储中。每当页面重新加载时,Vuex的状态就会被重新初始化
A:存储的数据敏感性:确保不要存储敏感的用户信息或令牌等安全相关的数据。对于敏感数据,应采取适当的加密措施。
B:存储的数据大小限制:本地存储(如LocalStorage)对存储数据的大小有限制。确保你的状态数据不会超过本地存储的容量限制,以避免存储失败或影响性能。
C:存储选择:默认使用LocalStorage进行状态存储,也可以选择其他本地存储方式。
D:黑名单和白名单:提供了黑名单和白名单机制,用于指定需要或不需要持久化的状态模块或属性。用于过滤敏感或不必要的数据,减少存储开销和保护隐私。
E:存储兼容性:需要考虑存储的数据格式的兼容性。确保在状态结构发生变化时,向后兼容旧数据。可以使用版本控制或数据迁移策略来管理数据格式变化。
F:清除存储:如果需要在用户退出登录或其他特定情况下清除持久化的状态,可以调用插件提供的方法来清除本地存储中的数据
npm install vuex-persistedstate
import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate';
Vue.use(Vuex);
const store = new Vuex.Store({
// 状态定义和其他配置...
plugins: [createPersistedState()]
});
export default store;
(store) => {
// 每次 mutation 后都会调用这个回调函数
store.subscribe((mutation, state) => {
// 将状态存储到LocalStorage或SessionStorage
localStorage.setItem('vuex-state', JSON.stringify(state));
});
}
const savedState = localStorage.getItem('vuex-state');
3:使用Cookie:Cookies是一种在浏览器中存储少量数据的机制,有大小限制(通常为4KB),会在每个请求中自动发送到服务器端
4:使用IndexedDB:IndexedDB是一种浏览器内置的NoSQL数据库,可以用于在客户端存储大量结构化数据。
(store) => {
// 打开或创建IndexedDB数据库
const request = window.indexedDB.open('vuex-db', 1);
request.onerror = (event) => {
console.error('IndexedDB error:', event.target.error);
};
request.onsuccess = (event) => {
const db = event.target.result;
// 获取一个事务对象
const transaction = db.transaction(['vuex-store'], 'readwrite');
const objectStore = transaction.objectStore('vuex-store');
// 保存状态到IndexedDB
objectStore.put(store.state, 1);
transaction.oncomplete = () => {
console.log('Vuex state saved to IndexedDB.');
};
};
}
const request = window.indexedDB.open('vuex-db', 1);
5:使用服务端存储(接口方式):可以将Vuex的状态存储在服务器端的数据库或缓存中。这样可以实现跨设备和跨会话的状态共享,并提供更强大的数据管理和安全性。
1:推荐使用插件方案,简单
2:常用使用LocalStorage进行持续化,提交进行存储,获取进行读取