---- AI试用 ---域名问题某些图片和js资源无法访问,导致一些代码实例无法运行!(代码里gzui.net换成momen.vip即可)

Vue项目集成vuex-persistedstate

前端开发 蚂蚁 1045℃ 0评论

来源 https://fugary.com/?p=49

Vue项目中使用Vuex作为状态管理已经是比较通用的做法了,新建Vue项目的时候就可以选择集成Vuex,其实Vuex本质上类似全局的变量存储,方便在所有Vue组件中共享,而且也可以动态改变状态。

在单页应用中Vue项目集成Vuex也就足够基本使用了,但是刷新页面的时候数据都会被清空,在某些情况下,我们需要这些状态能保存下来,比如登录后的用户信息、AccessToken、主题配置等。

这里就需要vuex-persistedstate,他可以把数据保存到localStorage或者Cookie

安装vuex-persistedstate

GitHub地址:https://github.com/robinvdvleuten/vuex-persistedstate

安装:

npm install vuex-persistedstate --save

安装好之后就要做一些配置了

配置vuex-persistedstate

store/index.js中使用

import Vue from 'vue'
import Vuex from 'vuex'
import ThemeStore from './ThemeStore'
import createPersistedState from 'vuex-persistedstate'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {},
  mutations: {},
  actions: {},
  modules: {
    Theme: ThemeStore
  },
  plugins: [createPersistedState()]
})

这样就集成成功了,默认情况下,使用localStorage作为存储。

使用Cookie存储

官方已经提供使用cookie存储的教程,比较方便集成,先要安装js-cookie,作为操作cookie的工具。

注意:其实很多公司不允许直接用js修改cookie了,认为是不安全的操作,cookie只能后台服务端修改,httpOnly模式,个人建议不要使用Cooke来存储

npm install js-cookie --save

集成如下:

import { Store } from "vuex";
import createPersistedState from "vuex-persistedstate";
import * as Cookies from "js-cookie";
const store = new Store({
  // ...
  plugins: [
    createPersistedState({
      storage: {
        getItem: (key) => Cookies.get(key),
        // Please see https://github.com/js-cookie/js-cookie#json, on how to handle JSON.
        setItem: (key, value) =>
          Cookies.set(key, value, { expires: 3, secure: true }),
        removeItem: (key) => Cookies.remove(key),
      },
    }),
  ],
});

部分持久化

目前集成后,vuex-persistedstate默认会把所有state都保存到localStorage之中,其实对于大部分页面来讲,需要store存储的数据很多,但是需要持久化到localStorage的数据并不多,而且localStorage存储大量数据也不合适,因此我们可以自定义部分数据持久化,部分数据只在页面上使用。

vuex-persistedstate提供有一个reducer函数,可以自定义存储Key,或者使用paths参数,建议使用paths参数比较简单

// 非Module格式:xxxx
// 使用了Module的格式:ModuleName.xxxx,这里持久化的是Theme Module下面的persistData数据
const PERSIST_PATHS = ['Theme.persistData']
export default new Vuex.Store({
  state: {},
  mutations: {},
  actions: {},
  modules: {
    Theme: ThemeStore
  },
  plugins: [createPersistedState({
    paths: PERSIST_PATHS
  })]
})

这就算集成完成了,需要持久化的数据手动添加到PERSIST_PATHS中就可以了。

GitHub地址:https://github.com/fugary/simple-element-ui-template

转载请注明:有爱前端 » Vue项目集成vuex-persistedstate

喜欢 (0)or分享 (0)