Appearance
简易 vuex - mini-vuex
javascript
export let Vue;
class Store {
constructor(options) {
let state = options.state;
let getters = options.getters;
let mutations = options.mutations;
let actions = options.actions;
this.mutations = mutations;
this.actions = actions;
// 这里我们期望state 是响应视图
// this.state = state;
// 借用vue本身的响应式的通知机制
// state 会将需要的依赖手机在 Dep 中
this._vm = new Vue({
data: {
// 在定义数据vue对$或者_的退让,不进行代理
$$state: state,
},
});
this.getters = {};
Object.keys(getters).forEach((gettersKey) => {
Object.defineProperty(this.getters, gettersKey, {
get() {
return getters[gettersKey](state);
},
});
});
}
get state() {
return this._vm._data.$$state;
}
commit(type, payload) {
this.mutations[type](this.state, payload);
}
dispatch(type, payload) {
this.actions[type](this.state, payload);
}
}
const install = (_Vue) => {
Vue = _Vue;
Vue.mixin({
beforeCreate() {
// 所有组件都定义一个$store 属性可以用来获取 store实例
if (this.$options.store) {
// 根
this.$store = this.$options.store;
} else if (this.$parent && this.$parent.$store) {
this.$store = this.$parent.$store;
}
},
});
};
export default {
Store,
install,
};
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
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