Vuejs 如何定制使用vuex-persistedstate状态持久化插件

5 篇文章 0 订阅
5 篇文章 0 订阅

第零步,按照惯例,先贴出传送门

代码:https://github.com/robinvdvleuten/vuex-persistedstate

API:https://github.com/robinvdvleuten/vuex-persistedstate#api

第一步,安装

npm install --save vuex-persistedstate

第二步,示例代码

/* module.js */
export const dataStore = {
  state: {
    data: []
  }
}

/* store.js */
import { dataStore } from './module'

const dataState = createPersistedState({
  paths: ['data']
})

export new Vuex.Store({
  modules: {
    dataStore
  },
  plugins: [dataState]
})

第三步,定制持久化的state路径,简化存储的内容

从api我们能看到有一个选项是paths

paths <Array>: An array of any paths to partially persist the state. If no paths are given, the complete state is persisted. If an empty array is given, no state is persisted. Paths must be specified using dot notation. If using modules, include the module name. eg: "auth.user" Defaults to undefined.

比如,我们在做网页的时候,通常会记录用户的搜索记录,以便后面自动推荐。或者是用户刷新页面了,也可以存储到以往的搜索历史,如果仅仅只是放在vuex中,刷新就会丢失数据了。如果自己手工去维护数据到localStorage又比较繁琐。我们就可以定制化一些参数,比如将查询相关的vuex状态都归类到search里面,就可以使用以下配置,简化vuex持久化的数据。

const searchState = createPersistedState({ paths: ['search'] })

另外呢,为了保证数据在用户关闭页面之后自动清除,而不需要额外的操作,我们还可以将存储的方式调整为sessionStorage。

const searchState = createPersistedState({ paths: ['search'], storage: window.sessionStorage })

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值