vue的watch实现原理
使用方式
new Vue({
data: {
count: 100,
countText: ''
},
watch: {
count(newVal, oldVal) {
this.countText = newVal + '秒'
}
}
})
实现原理
class Vue {
constructor(options) {
let { data, watch } = options
this.$data = {}
for (let key in data) {
let value = data[key]
Object.defineProperty(this.$data, key, {
configurable: true,
enumerable: true,
get: () => {
return value
},
set: (newVal) => {
let oldVal = data[key]
value = newVal
if (watch[key]) {
const fn = watch[key]
fn.call(this, newVal, oldVal)
}
}
})
}
}
}