Vuex实现状态持久化
vuex的数据是保存在内存中的,浏览器一刷新就会消失。所以要对Vuex的数据进行持久化管理
刚开始改变数据,调用 this.$store.commit('CHANGE_FLAG',!this.flag)
,改变完的数据会存储在localStorge
里面,当页面加载的时候调用 this.$store.dispatch('LOAD_IONF')
,从localStorge
里面拿数据,并把拿到的数据重新复制给vuex的state
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| <template> <div> <h1>从vuex中读取的数据:{{flag}} </h1> <button @click="changeInfo">更改数据</button> </div> </template>
<script> import {mapState} from 'vuex' export default { name: 'VuexPermanent', computed: { ...mapState(['flag']) }, data() { return {} }, mounted() { // 加载数据 this.$store.dispatch('LOAD_IONF') }, methods: { changeInfo() { // 存储(改变数据) this.$store.commit('CHANGE_FLAG',!this.flag) } }, } </script>
<style lang="scss" scoped>
</style>
|
store->index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| import Vue from 'vue' import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({ state: { flag: false }, mutations: { CHANGE_FLAG(state,value) { state.flag = value window.localStorage.setItem('flag',JSON.stringify(state.flag)) }, SET_INFO(state,value) { state.flag = value } }, actions: { LOAD_IONF({commit}) { let flag = JSON.parse(window.localStorage.getItem('flag')) if (flag != null) { commit('SET_INFO', flag) } } } })
|

不管怎么刷新,数据也不会边(vuex中初始值的数据是false)