Vuex可以保存组件之间的共享数据,相当于一个全局的数据仓库,所有组件都可以获取和修改数据。组件内私有的数据可以放到组件的data中。props中存放的是父组件传过来的数据。
一.state&mutations
1 | //新建store.js文件 |
2 | import Vue from 'vue' |
3 | import Vuex from 'vuex' |
4 | Vue.use(Vuex) |
5 | |
6 | const store = new Vuex.Store({ |
7 | state: {//类似组件中的data |
8 | count: 0 |
9 | }, |
10 | mutations: {//类似组件中的methods,操作数据 |
11 | increment (state) { |
12 | state.count++ |
13 | } |
14 | } |
15 | }) |
16 | //在组件中可以通过this.$store.state获取状态对象,通过this.$store.commit方法触发状态变更 |
17 | this.$store.commit('increment') |
18 | console.log(this.$store.state.count) // -> 1 |
二.Getter
getter(可以认为是store的计算属性)。就像计算属性一样,getter的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
1 | const store = new Vuex.Store({ |
2 | state: { |
3 | todos: [ |
4 | { id: 1, text: '...', done: true }, |
5 | { id: 2, text: '...', done: false } |
6 | ] |
7 | }, |
8 | getters: { |
9 | doneTodos: state => { |
10 | return state.todos.filter(todo => todo.done) |
11 | } |
12 | } |
13 | }) |
14 | //在组件中访问:this.$store.getters.xxx |
15 | computed: { |
16 | doneTodosCount () { |
17 | return this.$store.getters.doneTodosCount |
18 | } |
19 | } |
三.Action
action类似mutation,不同在于:
- action提交的是mutation,而不是直接变更状态。
- action可以包含任意异步操作。
1 | const store = new Vuex.Store({ |
2 | state: { |
3 | count: 0 |
4 | }, |
5 | mutations: { |
6 | increment (state) { |
7 | state.count++ |
8 | } |
9 | }, |
10 | actions: { |
11 | increment (context) { |
12 | context.commit('increment') |
13 | } |
14 | } |
15 | }) |
四.Module
应用程序复杂,管理的状态较多时,store对象可以分割成模块。
1 | const moduleA = { |
2 | state: { ... }, |
3 | mutations: { ... }, |
4 | actions: { ... }, |
5 | getters: { ... } |
6 | } |
7 | |
8 | const moduleB = { |
9 | state: { ... }, |
10 | mutations: { ... }, |
11 | actions: { ... } |
12 | } |
13 | |
14 | const store = new Vuex.Store({ |
15 | modules: { |
16 | a: moduleA, |
17 | b: moduleB |
18 | } |
19 | }) |
20 | |
21 | store.state.a // -> moduleA 的状态 |
22 | store.state.b // -> moduleB 的状态 |