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

代码: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 })

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐