哈喽,各位小伙伴,欢迎来到我是wangfang呀的博客!我是我是wangfang呀,虽然还在编程的“菜鸟”阶段,但我已经迫不及待地想和大家分享我一路上踩过的坑和学到的小技巧。如果你也曾为bug头疼,那么你来对地方了!今天的内容希望能够给大家带来一些灵感和帮助。

概述:Vuex 状态持久化的需求

在 Vue.js 应用中,Vuex 是官方推荐的状态管理库,用于集中管理组件之间的共享状态。它通过 store 存储状态,并且允许通过 mutations 来修改状态。然而,Vuex 默认是将状态保存在内存中,当页面刷新时,所有的状态都会丢失。

为了在页面刷新后保持状态,通常需要将 Vuex 中的状态持久化,即将状态保存在浏览器的 localStoragesessionStorage 中。这样,即使页面刷新,状态也能恢复,提升用户体验。

Vuex 状态持久化的需求通常出现在以下场景:

  • 用户登录状态:保持用户登录信息,即使页面刷新也不会丢失。
  • 购物车:存储购物车的商品信息,防止刷新后购物车清空。
  • 用户设置:保存用户的个性化设置或主题等信息。

使用 Vuex-persistedstate 插件:将 Vuex 状态存储在 localStorage 或 sessionStorage 中

为了解决 Vuex 状态持久化问题,我们可以使用 vuex-persistedstate 插件。该插件能够帮助我们将 Vuex 的状态自动存储到浏览器的 localStoragesessionStorage 中,并在页面刷新时恢复状态。

步骤 1:安装 vuex-persistedstate 插件

首先,需要安装 vuex-persistedstate 插件。

npm install vuex-persistedstate

步骤 2:在 Vuex 中配置持久化

store 中使用 vuex-persistedstate 插件,设置插件选项来指定存储方式(localStoragesessionStorage),并使其与 Vuex 进行集成。

// store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate';Vue.use(Vuex);const store = new Vuex.Store({state: {user: null,cart: [],theme: 'light'},mutations: {setUser(state, user) {state.user = user;},setCart(state, cart) {state.cart = cart;},setTheme(state, theme) {state.theme = theme;}},actions: {setUser({ commit }, user) {commit('setUser', user);},setCart({ commit }, cart) {commit('setCart', cart);},setTheme({ commit }, theme) {commit('setTheme', theme);}},plugins: [createPersistedState({key: 'my-app', // localStorage/sessionStorage 的 key 值storage: window.localStorage // 使用 localStorage 存储})]
});export default store;

步骤 3:在主入口文件中使用 Vuex Store

main.js 中引入并使用配置好的 Vuex store。

// main.js
import Vue from 'vue';
import App from './App.vue';
import store from './store';  // 引入 Vuex storeVue.config.productionTip = false;new Vue({render: h => h(App),store  // 将 store 注入到 Vue 实例中
}).$mount('#app');

步骤 4:使用 Vuex 存储状态

在组件中,您可以像平常一样使用 this.$store.state 获取 Vuex 状态,并使用 this.$store.committhis.$store.dispatch 修改状态。

<template><div><p>User: {{ user }}</p><p>Cart: {{ cart.length }} items</p><p>Theme: {{ theme }}</p><button @click="changeTheme">Change Theme</button><button @click="logout">Logout</button></div>
</template><script>
export default {computed: {user() {return this.$store.state.user;},cart() {return this.$store.state.cart;},theme() {return this.$store.state.theme;}},methods: {changeTheme() {const newTheme = this.theme === 'light' ? 'dark' : 'light';this.$store.dispatch('setTheme', newTheme);},logout() {this.$store.dispatch('setUser', null);  // 清除用户信息this.$store.dispatch('setCart', []);    // 清空购物车}}
};
</script>

步骤 5:测试持久化功能

  1. 刷新页面,您会发现 usercarttheme 等数据依然存在。

  2. 通过 localStorage 检查数据是否成功保存和恢复:

    • 打开浏览器的开发者工具,查看 Application -> Local Storage -> my-app 键,您会看到 Vuex 状态被存储在其中。

存储方式:localStoragesessionStorage

  • localStorage:数据长期保存在浏览器中,除非被手动清除。
  • sessionStorage:数据仅在一个会话期间有效,关闭浏览器窗口后数据会丢失。

您可以根据需求在 createPersistedState 中配置存储方式:

storage: window.localStorage  // 永久存储
// 或者
storage: window.sessionStorage  // 会话存储

代码示例:使用插件实现状态持久化

// store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate';Vue.use(Vuex);const store = new Vuex.Store({state: {user: null,cart: [],theme: 'light'},mutations: {setUser(state, user) {state.user = user;},setCart(state, cart) {state.cart = cart;},setTheme(state, theme) {state.theme = theme;}},actions: {setUser({ commit }, user) {commit('setUser', user);},setCart({ commit }, cart) {commit('setCart', cart);},setTheme({ commit }, theme) {commit('setTheme', theme);}},plugins: [createPersistedState({key: 'my-app',  // 设置 key 值storage: window.localStorage  // 使用 localStorage 存储})]
});export default store;

小结

Vuex 状态持久化是通过将 Vuex 中的状态存储到浏览器的 localStoragesessionStorage 中来实现的。使用 vuex-persistedstate 插件,开发者可以非常方便地在 Vue 应用中实现状态持久化,确保页面刷新时数据不会丢失。通过这种方式,可以保持用户的登录状态、购物车数据、用户设置等信息,即使刷新页面也能恢复。

好啦,今天的内容就先到这里!如果觉得我的分享对你有帮助,给我点个赞,顺便评论吐个槽,当然不要忘了三连哦!感谢大家的支持,记得常回来,我是wangfang呀等着你们的下一次访问!