欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

vuex-persistedstate 持久化插件

程序员文章站 2022-06-06 21:16:16
...

既然是一个插件,那首先我们得安装它,然后再使用

npm install --save vuex-persistedstate
// 或
npm i -S vuex-persistedstate

在 store 文件夹下的 index.js 文件中我们引入:

import Vuex from 'vuex'
import Vue from 'vue'
import createPersistedState from 'vuex-persistedstate' // 引入持久化插件
import * as Cookies from 'js-cookie' // 引入cookies库

使用:

Vue.use(Vuex)
// 系统级别的全局状态
import app from './app'
// 创建store实例
const store = new Vuex.Store({
  modules,
  state: app.state,
  getters: app.getters,
  actions: app.actions,
  mutations: app.mutations,
  strict: process.env.NODE_ENV !== 'production',
  plugins: [
  		createPersistedState({ 
  			storage: window.localStorage 
  		})
  	]
})

vuex-persistedstate默认使用localStorage来固化数据,一些特殊情况要如何应对呢?(如:safari的无痕浏览模式)

1.使用sessionStorage的情况和localStorage一样在plugins 数组中改为: window.sessionStorage

// 创建store实例
const store = new Vuex.Store({
  modules,
  state: app.state,
  getters: app.getters,
  actions: app.actions,
  mutations: app.mutations,
  strict: process.env.NODE_ENV !== 'production',
  plugins: [
  		createPersistedState({ 
  			storage: window.sessionStorage 
  		})
  	]
})

2.使用cookie的情况

// 创建store实例
const store = new Vuex.Store({
  modules,
  state: app.state,
  getters: app.getters,
  actions: app.actions,
  mutations: app.mutations,
  strict: process.env.NODE_ENV !== 'production',
  plugins: [
   createPersistedState({
      storage: {
       getItem: key => Cookies.get(key),
       setItem: (key, value) => Cookies.set(key, value, { expires: 7 }),
       removeItem: key => Cookies.remove(key) } })
	]
})

export default store

请参考以下博客:
https://github.com/robinvdvleuten/vuex-persistedstate
https://github.com/js-cookie/js-cookie
https://www.jianshu.com/p/e88ab068820b
https://www.cnblogs.com/ichenchao/articles/11589769.html
https://www.lovean.com/mip/view-10-331566-0.html

相关标签: Vue学习总结 Vue