仿Vuex响应式源码实现
state响应式原理
我们都知道store里的state是响应式变化的,那是怎么实现的呢?
原理还是利用了Object.defineProperty Object.keys()方法会返回一个由给定对象的自身可枚举属性组成的数组,数组中属性名的排列顺序和使用for…in循环遍历该对象时返回的顺序一致
代码如下(示例):
var reactive = obj => {
let deps = new Dep
Object.keys(obj).forEach(key => {
let value = obj[key]
Object.defineProperty(obj, key, {
get() {
deps.getters()
return value
},
set(newValue) {
value = newValue
deps.setters()
}
})
})
return obj
}
vuex代码如下:
class Store {
constructor(options = {}) {
const { state, mutations } = options
this._vm = reactive(state)
this._mutations = mutations
}
get state() {
return this._vm
}
commit(type, params) {
const entry = this._mutations[type]
if (!entry) {
return
}
entry(this.state, params)
}
}
const store = new Store({
state: {
count: 0
},
mutations: {
addCount(state, p) {
state.count += p
}
},
})
var stop = watchEffect(() => {
var str = `${store.state.count}`
document.getElementById("app").innerText = str
})
document.getElementById('btn').addEventListener('click', function () {
store.commit("addCount", 1)
})
对state对象进行监听,并且定义commit方法,调用时直接执行store实例上的mutations方法
|