我正在尝试制作一个没有后端的应用程序,并且我正在使用 Vue 和 Vuex 在我的应用程序商店中设置一些状态。有没有办法在设置并执行浏览器刷新后保留此状态而不调用服务器......或者在页面刷新后它总是默认返回默认初始状态值?
正如其他答案中所述,有多种方法可以保存状态。
探索本地存储和 Vuex 有一些方法可以实现这一点。
存储在本地存储中的所有内容都是存储为键值对的字符串。要将其存储在您编写的本地存储中
// Store value "value" with key "key"
localStorage.setItem('key', 'value');
// Load data from local storage store as a variable
let val = localStorage.getItem('key');
Run Code Online (Sandbox Code Playgroud)
如果要存储对象,请将其转换为 JSON 字符串
// Convert object to an JSON string and store it with key "key"
localStorage.setItem('key', JSON.stringify(object));
// Retrieve data and convert JSON string to object
let obj = JSON.parse(localStorage.getItem('key'));
Run Code Online (Sandbox Code Playgroud)
您可以从 Vuex 使用它,存储某些值或整个存储。
例如,在 vuex 函数中,您可以检查本地存储是否有值,如果没有则从 api 检索它:
...
if (localStorage.getItem('key')) {
// Use data from local storage
} else {
// Get it from an api/other source
}
...
Run Code Online (Sandbox Code Playgroud)
如果你想将整个商店存储在本地存储中(并不是说你应该这样做)并且你想确保始终拥有最新的保存,你可以在 Vuex 中创建一个订阅,每次商店更新时都会触发该订阅。
// Create a subscription that stores updates on every mutation
store.subscribe((mutation, state) => {
// Store the store object as a JSON string
localStorage.setItem('store', JSON.stringify(state));
});
Run Code Online (Sandbox Code Playgroud)
创建 Vue 应用程序后,您可以调用一个操作来检查本地存储,如果存储存在,则加载它
if (localStorage.getItem('store')) {
// Replace the store state object with the stored object
this.replaceState(
Object.assign(state, JSON.parse(localStorage.getItem('store')))
);
...
}
Run Code Online (Sandbox Code Playgroud)
这是如何在本地存储中存储的快速浏览。您必须考虑如何重置/使本地存储中的数据无效。您还必须决定存储什么。如果你应该有某种时间戳等等。
有一些 vuex 插件可以为你做一些事情。看看https://github.com/vuejs/awesome-vue看看你是否发现了什么。
| 归档时间: |
|
| 查看次数: |
3896 次 |
| 最近记录: |