一直都知道vue3使用了proxy来替代Object.defineProperties来做依赖收集, 那就来个小例子
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
| var Vue = { deps: new Set(), currentEffect: null, watchEffect(ef) { Vue.currentEffect = ef; ef(); }, track() { this.deps.add(this.currentEffect) }, trigger() { this.deps.forEach(ef => ef()) }, reactive(target) { const handlers = { get() { const result = Reflect.get(...arguments); Vue.track(); return result }, set() { const result = Reflect.set(...arguments); Vue.trigger(); return result } } return new Proxy(target, handlers) } }
const { watchEffect, reactive } = Vue;
var SaledCar = reactive({ price: 10000, count: 10 }); var achievement = 0; watchEffect(() => { achievement = SaledCar.price * SaledCar.count }) console.log(`改价之前: ${achievement} 元`) SaledCar.price = 12000; console.log(`改价之后: ${achievement} 元`)
|