Vuex状态、数据持久化(vue2、vue3状态数据持久化)

简介:Vuex是一个仓库,是vue的状态管理工具,存放公共数据,任何组件都可以使用vuex里的公共数据。Vuex提供了插件系统,允许我们使用 vuex-persistedstate插件,将Vuex的状态持久化到本地存储中,解决页面刷新或重新打开应用时状态丢失的问题;这里记录一下Vuex数据持久化的几种实现方案。

⭐这里先介绍一下Vuex里面属性及使用

1、属性介绍

 //1、state存放状态和数据
 state: {
    flag: 0,
  },

  //2、mutations修改状态和数据
  mutations: {
    defineTest(state, i) {
      state.flag = i;
    }
  },

  //3、getters计算属性
  getters: {
  },

  //4、actions异步操作
  actions: {
  },

  //5、modules模块化
  modules: {
  },

  //6、持久化插件
  plugins: [
     vuexPersistedState({
       storage: window.localStorage, // 指定存储引擎  
     }),
  ],

2、页面调用

 //state的调用方式 1
 computed: {  
    ...mapState(['flag']) // 将 this.$store.state.count 映射为组件内的 count 计算属性  
 },
 <div>{{ flag }}</div>   
 
 //state的调用方式 2
 <div v-if="this.$store.state.flag">测试数据</div>


 //mutations的调用方式 1
 methods: {  
   // 将 this.increment() 映射为this.$store.commit('increment')      
   ...mapMutations(['increment']),  
   // 触发事件
   this.increment();
 }  
 
 //mutations的调用方式 2
 this.$store.commit('defineTest', i)

 //actions的调用方式
 this.$store.dispatch('someAction', payload);

⭐Vue2中,Vuex状态、数据持久化

一、通过手写函数和plugins,实现状态、数据持久化话;

1、新建pluginPersist.js文件,并导出存储函数

/**
 * 
 * @param {状态、数据持久化} store 
 */
export default function (store) {
    // console.log(store);
    // 存
    const KEY = 'VUEX:STATE';
    //这里表示 页面关闭 或 刷新 时存储
    window.addEventListener("beforeunload", () => {
        localStorage.setItem(KEY, JSON.stringify(store.state))
    })
    // 取
    try {
        const state = JSON.parse(localStorage.getItem(KEY));
        if (state) {
            store.replaceState(state);
        }
    } catch (err) {
        console.log(err);
    }
}

2、在store中,在plugins里引入挂载使用;plugins插件中的函数会在创建仓库时执行,插件的本质就是一个函数

import Vue from 'vue'
import Vuex from 'vuex'
import pluginPersist from "./pluginPersist"

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {  
    // ...状态、数据 
  },  
  mutations: {  
    // ...修改状态、数据
  },  
  actions: {  
    // ...动作函数 
  },  
  getters: {  
    // ...计算属性
  },  
  modules: {
    // ...模块化
  },
    //这里使用
  plugins: [pluginPersist],
 
})

export default store;

二、通过手写db对象方法,实现数据、状态持久化;

1、新建localStorage.js文件,创建db对象,然后导出db方法

var localStorage = window.localStorage;
const db = {
    /** 
     * 更新状态 
     */
    save(key, value) {
        // console.log(key, value);
        // 页面关闭或刷新时存储
        // window.addEventListener("beforeunload", () => {
        //     localStorage.setItem(key, JSON.stringify(value))
        // })
        // 触发该事件时存储 二选一
        localStorage.setItem(key, JSON.stringify(value));
    },
    /** 
     * 获取状态,如果有状态值,获取最新状态值;如果没有,获取默认值 
     */
    get(key, getSaveVal = null) {
        // console.log(key, getSaveVal);
        try {
            return JSON.parse(localStorage.getItem(key)) || getSaveVal;
        } catch (err) {
            console.log(err);
        }
    },
    /** 
     * 移除状态 
     */
    remove(key) {
        // console.log(key);
        localStorage.removeItem(key);
    },
    /** 
     * 清空状态 
     */
    clear() {
        localStorage.clear();
    }
};
export default db;

2、在store中引入使用

import Vue from 'vue'
import Vuex from 'vuex'
import db from './localStorage';

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    // 初始化时 默认获取
    state1: db.get('STATE1') || null,
  },
  mutations: {
    SET_STATE1: (state, value) => {
      state.state1++
      //调用SET_STATE1方法时 这里存储
      db.save('STATE1', state.state1);
    },
  },
  actions: {  
    // 动作函数 
  },  
  getters: {  
    // 计算属性
  },  
  modules: {
    // 模块化
  },
    // 插件
  plugins: [],

})

export default store

3、组件中调用SET_STATE1方法,并传值data

methods: {
    choseBtn(){
      this.$store.commit("SAVE_DOTS", this.data);
    }
},

三、通过vue插件vuex-persistedstate 或 vuex-plugin-persistedstate实现数据、状态持久化;

1、安装依赖

npm install vuex-persistedstate --save  
//或者  
cnpm install vuex-persistedstate --save 
//或者
yarn add vuex-persistedstate

--save是安装在生产环境,开发和生产都需要用到

//查看插件的依赖项
npm ls vuex-persistedstate

Tips:vuex-persistedstate 和 vuex-plugin-persistedstate 是同一个插件的不同引用方式,它们都是用来持久化 Vuex 状态管理的插件,可以将 Vuex 中的状态保存到本地存储(如 localStorage 或 sessionStorage)中,以便在刷新页面或重新打开应用时恢复这些状态;persist目前已经弃用;

2、引入使用

import Vue from 'vue';  
import Vuex from 'vuex';  
import createPersistedState from 'vuex-persistedstate';  
  
Vue.use(Vuex);  
  
export default new Vuex.Store({  
  state: {  
    // ...你的状态定义  
  },  
  mutations: {  
    // ...你的变更函数定义  
  },  
  actions: {  
    // ...你的动作函数定义  
  },  
  getters: {  
    // ...你的计算属性定义  
  },  
  modules: {
    // ...模块化
  },
  plugins: [  
    createPersistedState({  
      storage: window.localStorage, // 或者使用 sessionStorage  
    }),  
  ],  
});

3、注意事项:

  • createPersistedState 函数创建了一个插件实例;

  • 可以将存储选项(如 localStorage 或 sessionStorage)作为参数传递给它,插件默认使用 localStorage,但是可以根据需要选择其他存储方式;

  • vuex-persistedstate 插件默认会持久化 Vuex 中的所有状态,如果你只想持久化部分状态,可以通过配置插件的 paths 选项来实现

createPersistedState({  
  storage: window.localStorage,  
  // 只持久化这些路径下的状态  
  paths: ['some', 'partial', 'state'] 
})

在上面的配置中,只有 state.some/partial/state 路径下的状态会被持久化;其它状态在页面刷新或重新加载时不会得到恢复。



⭐Vue3中,Vuex状态、数据持久化

Vue3中的数据、状态持久化,可以通过Pinia插件实现,是vue3官方指定的持久化实现方案,地址在这:

Pinia官网icon-default.png?t=N7T8https://pinia.vuejs.org/zh/

好的,下面是一个完整的示例,演示如何使用 vuex-persistedstate 库实现 Vuex 数据持久化: 1. 创建一个 Vue3 项目,并安装 vuexvuex-persistedstate 库: ``` vue create my-app cd my-app npm install vuex vuex-persistedstate ``` 2. 在 src 目录下创建一个 store 目录,并在其中创建一个 index.js 文件: ```javascript import { createStore } from 'vuex'; import createPersistedState from 'vuex-persistedstate'; const store = createStore({ state: { count: 0, }, mutations: { increment(state) { state.count++; }, decrement(state) { state.count--; }, }, plugins: [ createPersistedState({ storage: window.localStorage, }), ], }); export default store; ``` 以上代码中,我们创建了一个名为 `store` 的 Vuex Store,并在其中定义了一个 `count` 状态和两个变更方法 `increment` 和 `decrement`。我们还在 `plugins` 选项中引入了 `createPersistedState`,并配置了 `storage` 选项为 `window.localStorage`,表示将数据存储到 localStorage 中。 3. 在 App.vue 文件中使用 Vuex Store: ```vue <template> <div> <p>Count: {{ count }}</p> <button @click="increment">Increment</button> <button @click="decrement">Decrement</button> </div> </template> <script> import { mapState, mapMutations } from 'vuex'; export default { computed: mapState(['count']), methods: mapMutations(['increment', 'decrement']), }; </script> ``` 以上代码中,我们通过 `mapState` 和 `mapMutations` 辅助函数将 Vuex Store 中的 `count` 状态和 `increment` 和 `decrement` 变更方法映射到组件中,从而可以在组件中使用这些状态和方法。 现在,我们可以启动应用并测试数据持久化功能了。在浏览器中打开 http://localhost:8080/,点击 Increment 按钮增加计数器的值,然后刷新页面,可以发现计数器的值仍然保持不变,说明数据已经被成功地存储到了本地存储中。 希望这个示例能够帮助你理解如何在 Vue3 中使用 vuex-persistedstate 库实现 Vuex 数据持久化
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北城笑笑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值