vuex组件 vuex-persistedstate
vuex可以进行全局的状态管理,但刷新后刷新后数据会消失,这是我们不愿意看到的。怎么解决呢,我们可以结合本地存储做到数据状态持久化,但是太麻烦每次都要操作,所以此时就可以利用vuex-persistedstate插件
安装
npm install vuex-persistedstate --save
1.使用vuex-persistedstate默认存储到localStorage
引入及配置:在store
下的index.js
中
import createPersistedState from "vuex-persistedstate" const store =newVuex.Store({ state: { count: 1 }, mutations: {}, actions: {},
// 当state中的值发生改变,此时localStorage中的vuex的值会同步把state中的所有值存储起来,当页面刷
新的时候,state的值会从localStorage自动获取vuex的value值,赋值到state中
plugins: [createPersistedState()]
})
2.使用vuex-persistedstate存储到sessionStorage
引入及配置:在store
下的index.js
中
import createPersistedState from "vuex-persistedstate" const store = new Vuex.Store({ state: {}, mutations: {}, actions: {}, plugins: [createPersistedState({ storage:window.sessionStorage // 同localStorage相同,只是将vuex的所有值存储到sessionStorage中 })] })
3.使用vuex-persistedstate指定需要持久化的state
引入及配置:在store
下的index.js
中
import createPersistedState from "vuex-persistedstate" const store = newVuex.Store({ state: { count: 0 }, mutations: {}, actions: {}, plugins: [createPersistedState({ storage:window.sessionStorage, reducer(val) { // 此时,当count发生改变的时候,就会调用此函数,并且val的值为当前state对象,return的值为当前本地存储的value值(本地存储的key值为vuex) return { count: val.count, changeCount: 'aaa' } } })] })
下边附上当前测试写的小demo,通过vuex控制组件中的加减运算
import Vue from 'vue' import Vuex from 'vuex' import createPersistedState from 'vuex-persistedstate' // 用于vuex状态管理与本地存储同步 Vue.use(Vuex) const Store = new Vuex.Store({ state: { count: 0, computedCount: 0, bb: 'bb' }, mutations: { add(state, n = 1) { state.count += n }, sub(state, n = 1) { state.count -= n } }, actions: { addSync(context, n) { setTimeout(function () { context.commit('add', n) }, 1000); }, subAsync(context, n) { setTimeout(() => { context.commit('sub', n) }, 1000) } }, getters: { comp(state) { return `当前的count为${state.count + 1}` } }, plugins: [ createPersistedState({ // 当state中的值发生变化的时候出发reduce函数 reducer(val) { console.log(val) // value值为当前state中的所有值对象 // return什么,localstorage中的key值为vuex的value值就是什么,而且是实时与state中的值保持同步 return { count: val.count || 0, computedCount: val.computedCount, aa: 1 } } }) ] }) export default Store
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2019-04-28 nodejs脚手架express-generator