当前位置: 首页 > article >正文

vuex持久化存储,手动保存到localStorage

vuex持久化存储,手动保存到localStorage

  • 一、store
    • 1. index.js
    • 2. modules/otherData.js
  • 二、保存到localStorage


一、store

1. index.js

提示:vuex持久化存储

import Vue from 'vue'
import Vuex from 'vuex'

// Vuex持久化存储
import VuexPersistence from 'vuex-persist'
const vuexLocal = new VuexPersistence({
  storage: window.localStorage
})

import otherData from "./modules/otherData.js"

Vue.use(Vuex)

const state = {}

const getters = {}

const mutations = {}

const actions = {}

export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions,
  modules: {
    // 模块命名,要在 js文件 声明namespaced: true才有用
    otherData,
  },
  plugins: [vuexLocal.plugin]
})

2. modules/otherData.js

提示:

// state
let state = {
  // 字典数据
  dictionaryData: [],
}

// getters
let getters = {
  // 字典数据
  get_dictionaryData(state) {
    return state.dictionaryData
  },
}

// mutations,以isShow属性为例
let mutations = {
  // 字典数据
  change_dictionaryData(state, data) {
    state.dictionaryData = data
  },
}

// ctions
let actions = {
  // 这里有两种写法,本质上一样
  // 写法1,无参
  asChangeShow(context) {
    context.commit('changeShow')
  },
  // 写法2,无参
  // asChangeShow({ commit }) {
  //     commit('changeShow')
  // }

  //有参
  asChangeName({ commit }, data) {
    commit('changeName', data)
  }
}
export default {
  namespaced: true, // 是否开启模块
  state,
  getters,
  mutations,
  actions
}


二、保存到localStorage

App.vue

created() {
  // 在页面加载时读取localStorage里的状态信息
  if (localStorage.getItem("store")) {
    this.$store.replaceState(Object.assign({}, this.$store.state, JSON.parse(localStorage.getItem("store"))))
  }
  // 在页面刷新时将vuex里的信息保存到localStorage里
  window.addEventListener("beforeunload", () => {
    localStorage.setItem("store", JSON.stringify(this.$store.state))
  })
}

http://www.kler.cn/a/589393.html

相关文章:

  • 奥林巴斯道Olympus DAO、奥拉丁模式、诺瓦银行、RWA模型合约解析开发
  • 大数据学习(70)-大数据调度工具对比
  • Navigation页面导航的使用
  • 基于javaweb的SpringBoot校园运动会管理系统设计与实现(源码+文档+部署讲解)
  • 6k ± 1 规则
  • 自然语言处理编程文档
  • 数组题型-二分查找-JS
  • 实战:自适应均衡的设计与实现
  • 【Docker】容器中安装cron命令
  • 使用 Docker 部署 MySQL 8
  • TensorFlow 基本原理与使用场景
  • 移除元素(快慢指针)
  • Linux第六讲----git与gdb
  • 文本检测-文本内容审核-文本过滤接口如何用PHP调用?
  • 市长海报/ Mayor‘s posters
  • L2-3 花非花,雾非雾
  • maven使用install将jar包编译到本地仓库管理
  • 【系统架构设计师】操作系统 - 文件管理 ② ( 位示图 | 空闲区域 管理 | 位号 | 字号 )
  • 牛客周赛 Round 85
  • ElementUI 表格中插入图片缩略图,鼠标悬停显示大图