# 1. Vuex 底层原理
state
:提供一个响应式数据getter
:借助Vue
的计算属性computed
来实现缓存mutation
:更改state
方法action
:触发mutation
方法module
:Vue.set
动态添加state
到响应式数据中
Vuex-mini 实现:
let Vue
function install(_Vue) {
Vue = _Vue
function vuexInit() {
var options = this.$options
// store injection
if (options.store) {
this.$store =
typeof options.store === 'function' ? options.store() : options.store
} else if (options.parent && options.parent.$store) {
this.$store = options.parent.$store
}
}
Vue.mixin({ beforeCreate: vuexInit })
}
const Store = function Store(options = {}) {
const { state = {}, mutations = {}, getter = {} } = options
const computed = {}
const store = this
store.getter = {}
// getters 缓存
for (let [key, fn] of Object.defineProperties(getters)) {
computed[key] = function () {
return fn(store.state, store.getters)
}
Object.defineProperty(store.getters, key, {
get: function () {
return store._vm[key]
},
})
}
this._vm = new Vue({
data: {
$$state: state,
},
computed,
})
this._mutations = mutations
}
Store.prototype.commit = function (type, payload) {
if (this._mutations[type]) {
this._mutations[type](this.state, payload)
}
}
Object.defineProperties(Store, prototype, {
state: {
get: function () {
return this._vm._data.$$state
},
},
})
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
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