Wills's blogs

Vuex

安装

直接下载/CDN引用

1
2
<script src="/path/to/vue.js"></script>
<script src="/path/to/vuex.js"></script>

npm

1
npm install vuex --save-dev

Yarn

1
yarn add vuex

在一个模块打包系统中,必须显示地通过Vue.use()来安装Vuex

1
2
3
4
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

Vuex是一个专为Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

使用例子如下:

main.js

1
2
3
4
5
6
7
8
import store from './store'
new Vue({
store,//注入组件当中
el: '#app',
render: h => h(App)
})

store.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
var state = {
count: 10
};
const mutations = {
increment(state) { //处理状态(数据)变化
state.count++;
},
decrement(state) {
state.count--;
}
};
const actions = {
increment: ({ //处理你要干什么,异步请求,判断,流程控制
commit
}) => {
commit('increment')
},
decrement: ({
commit
}) => {
commit('decrement');
},
clickOdd: ({
commit,
state
}) => {
if (state.count % 2 == 0) {
commit('increment')
}
},
clickAsync: ({
commit
}) => {
new Promise((resolve) => {
setTimeout(function() {
commit('increment');
resolve();
}, 1000);
});
}
};
const getters = {
count(state) {
return state.count;
},
getOdd(state) {
return state.count % 2 == 0 ? '偶数' : '奇数';
}
};
//需要导出Store对象
export default new Vuex.Store({
state,
mutations,
actions,
getters
});

App.vue

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
<template>
<div id="app">
<h3>welcome vuex-demo</h3>
<input type="button" value="增加" @click="increment">
<input type="button" value="减少" @click="decrement">
<input type="button" value="偶数才能点击+" @click="clickOdd">
<input type="button" value="点击异步" @click="clickAsync">
<div>
现在数字为: {{count}}, 它现在是 {{getOdd}}
</div>
</div>
</template>
<script>
import {mapGetters, mapActions} from 'vuex'
export default{
computed:mapGetters([
'count',
'getOdd'
]),
methods:mapActions([//分发action
'increment',//映射 this.increment() 为 this.$store.dispatch('increment')
'decrement',
'clickOdd',
'clickAsync'
])
}
</script>