状态管理与Vuex

在实际的业务中,经常有跨组件共享数据的需求,Vuex就是设计用来统一管理组件状态的,它定义了一系列规范来使用和操作数据,使组件的应用更高效。

引入Vuex之后统一对共享数据进行管理存放,在各个页面中可以利用commit方法提交mutation对共享数据进行修改。

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
// store/index.js
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
increment: state => state.count++,
decrement: state => state.count--
}
})

// Component.vue
export default {
computed: {
count() {
return this.$store.state.count;
}
},
methods: {
increment() {
return this.$store.commit("increment");
},
decrement() {
return this.$store.commit("decrement");
}
}
};