Open H246802 opened 5 years ago
function Vue (options) {
var Dep = null
let {data, computed} = options
this.data = data
this.computed = computed
var deps = [];
for (let key in this.data) {
Object.defineProperty(this, key, {
get: function () {
if (Dep) {
deps.push(Dep)
}
return this.data[key]
},
set: function (value) {
this.data[key] = value
deps.forEach(func => {
func()
})
}
})
}
for (let funcName in this.computed) {
this.computed[funcName] = this.computed[funcName].bind(this)
var value
Dep = function () {
value = this.computed[funcName]
}
value = this.computed[funcName]
Dep = null
Object.defineProperty(this, funcName, {
get: function () {
return value.call(this)
}
})
}
}
// 测试用例
var a = new Vue({
data: {
name: 'liyang'
},
computed: {
sayHi() {
return this.name + ', hi!'
}
}
})
简单模拟
Vue
的computed
功能: