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))
})
}