22
33为了更好地理解 Vuex app 中的数据流,我们来开发一个简单的计数器 app。注意:这个例子仅仅是为了更好地解释概念,在实际情况中并不需要在这种简单的场合使用 Vuex.
44
5- ### 引入并加载 Vuex
5+ ### Store
66
77``` js
88// store.js
99import Vue from ' vue'
1010import Vuex from ' vuex'
1111
1212Vue .use (Vuex)
13- ```
14-
15- ### 定义 App State
1613
17- ``` js
14+ // 应用初始状态
1815const state = {
1916 count: 0
2017}
21- ```
22-
23- ### 定义会被用到的 State Mutations
2418
25- ``` js
19+ // 定义所需的 mutations
2620const mutations = {
2721 INCREMENT (state ) {
2822 state .count ++
@@ -31,30 +25,25 @@ const mutations = {
3125 state .count --
3226 }
3327}
34- ```
35-
36- ### 定义可被调用的 Actions
3728
38- ``` js
39- const actions = {
40- increment : ' INCREMENT ' ,
41- decrement : ' DECREMENT '
42- }
29+ // 创建 store 实例
30+ export default new Vuex . Store ( {
31+ state ,
32+ mutations
33+ })
4334```
4435
45- ### 创建 Store 实例
36+ ### Actions
4637
4738``` js
48- export default new Vuex .Store ({
49- state,
50- mutations,
51- actions
52- })
39+ // actions.js
40+ export const increment = ({ dispatch }) => dispatch (' INCREMENT' )
41+ export const decrement = ({ dispatch }) => dispatch (' DECREMENT' )
5342```
5443
5544### 在 Vue 组件里使用
5645
57- ** Template **
46+ ** 模板 **
5847
5948``` html
6049<div >
@@ -64,29 +53,36 @@ export default new Vuex.Store({
6453</div >
6554```
6655
67- ** Script **
56+ ** 代码 **
6857
6958``` js
70- import store from ' ./store.js'
71-
72- export default {
73- computed: {
74- // 在 computed 属性内绑定 state
75- count () {
76- return store .state .count
59+ // 仅需要在根组件中注入 store 实例一次即可
60+ import store from ' ./store'
61+ import { increment , decrement } from ' ./actions'
62+
63+ const app = new Vue ({
64+ el: ' #app' ,
65+ store,
66+ vuex: {
67+ getters: {
68+ count : state => state .count
69+ },
70+ actions: {
71+ increment,
72+ decrement
7773 }
78- },
79- methods: {
80- increment: store .actions .increment ,
81- decrement: store .actions .decrement
8274 }
83- }
75+ })
8476```
8577
86- 你会注意到组件本身非常简单:它所做的仅仅是绑定到 state、然后在用户输入时调用 actions.
78+ 你会注意到组件本身非常简单:它所做的仅仅是绑定到 state、然后在用户输入时调用 actions。
8779
8880你也会发现整个应用的数据流是单向的,正如 Flux 最初所定义的那样:
8981
82+ 1 . 用户在组件中的输入操作触发 action 调用;
83+ 2 . Actions 通过分发 mutations 来修改 store 实例的状态;
84+ 3 . Store 实例的状态变化反过来又通过 getters 被组件获知。
85+
9086<p align =" center " >
9187 <img width =" 700px " src =" vuex.png " >
9288</p >
0 commit comments