Skip to main content

Vue 响应式原理

1. Vue2 响应式实现

Object.defineProperty

function defineReactive(obj, key, val) {
const dep = new Dep()

Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter() {
if (Dep.target) {
dep.depend()
}
return val
},
set: function reactiveSetter(newVal) {
if (newVal === val) return
val = newVal
dep.notify()
}
})
}

依赖收集

class Dep {
constructor() {
this.subscribers = new Set()
}

depend() {
if (Dep.target) {
this.subscribers.add(Dep.target)
}
}

notify() {
this.subscribers.forEach(sub => sub.update())
}
}

2. Vue3 响应式实现

Proxy

function reactive(target) {
return new Proxy(target, {
get(target, key, receiver) {
const res = Reflect.get(target, key, receiver)
track(target, key)
return res
},
set(target, key, value, receiver) {
const res = Reflect.set(target, key, value, receiver)
trigger(target, key)
return res
}
})
}