vue 使用 vuex-persist 让store实现更便捷的存储 localStorage

原文:

本文链接:https://blog.csdn.net/chu_geng/article/details/92579915

安装 vuex-persist,

我这里用的是yarn: yarn add vuex-persist

使用这是关于 vuex-persist 的文档 https://www.npmjs.com/package/vuex-persist有需要深度要了解的可以看一下这个

简单应用:

在全局的store中

引入 import VuexPersistence from 'vuex-persist'

并且使用

 

1、在全局的state声明一个值 如:

const state = {
query: {},
}

2、在mutations中写方法,当query变化的时候调用更新数据

const mutations = {
setDetailQuery (state, query) {
state.detailQuery = query
}
}

3、在 Store中添加vuex-persist的调用

export default new Vuex.Store({
state,
getters,
actions,
mutations,
plugins:[
new VuexPersistence({
reducer: state => ({
query: state.query //这个就是存入localStorage的值
})
}).plugin
]
})

4、在需要存localStorage 的页面调用

import {mapState, mapGetters, mapMutations} from 'vuex' //引入state,getters,mutations

在methods里边引入mutations 方法

...mapMutations(['setQuery'])

在需要的地方使用,例:

在created 里边 调用方法

this.setQuery(this.$route.query)

5、在需要取的页面

computed: {
...mapState(['query']),
},


————————————————
版权声明:本文为CSDN博主「chu_geng」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/chu_geng/article/details/92579915

posted @ 2019-09-26 11:26  鳳舞九天  阅读(411)  评论(0编辑  收藏  举报