vue的computed原理
使用方式
new Vue({
computed: {
countText() {
return this.count + '秒'
}
},
created() {
console.log(this.countText)
}
})
实现原理
// 大概实现原理
class Vue {
constructor(options) {
let { computed } = options
this.initComputed(computed)
}
initComputed(computedObj) {
// 使用Object.defineProperty挂载到this
for (let key in computedObj) {
const computedFn = computedObj[key]
Object.defineProperty(this, key, {
enumerable: true,
configurable: true,
get: () => {
return computedFn.apply(this) // 注意传入上下文,因为computed函数里要访问this
}
})
}
}
}