VueX状态持久化
# Vuex实现状态持久化
vuex的数据是保存在内存中的,浏览器一刷新就会消失。所以要对Vuex的数据进行持久化管理
刚开始改变数据,调用 this.$store.commit('CHANGE_FLAG',!this.flag)
,改变完的数据会存储在localStorge
里面,当页面加载的时候调用this.$store.dispatch('LOAD_IONF')
,从localStorge
里面拿数据,并把拿到的数据重新复制给vuex的state
<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>
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
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
store->index.js
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
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)
}
}
}
})
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
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
不管怎么刷新,数据也不会边(vuex中初始值的数据是false)
编辑 (opens new window)
上次更新: 2024/12/19, 09:15:30