如何实现持久化存储vuex

刷新vuex的值会回归初始化, 如果在保存到vuex时, 它能自动保存到浏览器本地, 默认从浏览器本地取呢?

自己写localStorage.setItem等 需要一个个写, 很麻烦自己写localStorage.setItem等 需要一个个写, 很麻烦

这里介绍一个vuex的插件包叫做vuex-persistedstate@3.2.1版本(配合vue2使用, 默认最新版是配合vue3使用)

npm i vuex-persistedstate@3.2.1

src/store/index.js中, 导入并配置 

import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 1. 用来存储登录成功之后,得到的 token
    token: ''
  },
  mutations: {
    // 2. 更新 token 的 mutation 函数
    updateToken (state, newToken) {
      state.token = newToken
    }
  },
  // 配置为 vuex 的插件
  plugins: [createPersistedState()]
})
  1. 这次再来重新登录, 查看浏览器调试工具vuex和浏览器本地存储位置, 是否自动同步进入

  2. 刷新网页看调试工具里vuex的默认值确实从本地取出了默认值, 保证了vuex的持久化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
为了实现Vuex模块的持久化存储,可以使用vuex-persistedstate插件。下面是实现Vuex模块持久化存储的步骤: 1. 安装vuex-persistedstate插件: ```shell npm i vuex-persistedstate@3.2.1 ``` 2. 在Vuex store中引入vuex-persistedstate插件: ```javascript import Vuex from 'vuex' import createPersistedState from 'vuex-persistedstate' const store = new Vuex.Store({ // ... plugins: [createPersistedState()] }) ``` 3. 在Vuex store中定义需要持久化存储的模块: ```javascript import user from './modules/user' const store = new Vuex.Store({ modules: { user }, plugins: [createPersistedState()] }) ``` 在上面的代码中,我们将user模块定义为需要持久化存储的模块。 4. 在需要持久化存储的模块中添加一个`namespaced`属性: ```javascript const user = { namespaced: true, // ... } ``` 5. 在需要持久化存储的模块中添加一个`mutations`属性: ```javascript const user = { namespaced: true, state: { // ... }, mutations: { // ... } } ``` 6. 在`mutations`中添加一个`RESTORE_MUTATION`: ```javascript import { RESTORE_MUTATION } from 'vuex-persistedstate' const user = { namespaced: true, state: { // ... }, mutations: { [RESTORE_MUTATION] (state, payload) { Object.assign(state, payload) }, // ... } } ``` 7. 在需要持久化存储的模块中添加一个`actions`属性: ```javascript const user = { namespaced: true, state: { // ... }, mutations: { // ... }, actions: { // ... } } ``` 8. 在`actions`中添加一个`init`方法: ```javascript const user = { namespaced: true, state: { // ... }, mutations: { // ... }, actions: { init ({ commit }) { commit(RESTORE_MUTATION, JSON.parse(localStorage.getItem('vuex'))) }, // ... } } ``` 9. 在Vue应用的入口文件中调用`init`方法: ```javascript import Vue from 'vue' import App from './App.vue' import store from './store' Vue.config.productionTip = false new Vue({ store, render: h => h(App), created () { this.$store.dispatch('user/init') } }).$mount('#app') ``` 现在,我们已经成功地实现Vuex模块的持久化存储
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值