Skip to content
On this page
js
const obj = {text: 'hello world'}

function effect() {
    document.body.innerText = obj.text
}

effect()

setTimeout(() => {
    obj.text = 'hello vue3'
}, 1000)

如何才能让 obj 变成响应式数据呢?

  • 当读取操作发生时,将当前副作用函数储存到一个”桶“中
  • 当设置操作发生时,从”桶“中取出副作用函数并执行
js
const bucket = new Set()

const data = {text: 'hello world'}

const obj = new Proxy(data, {
    get(target, key) {
        bucket.add(effect)
        return target[key]
    },
    set(target, key, newVal) {
        target[key] = newVal
        bucket.forEach(fn => fn())
    }
})

function effect() {
    document.body.innerText = obj.text
}

effect()

setTimeout(() => {
    obj.text = 'hello vue3'
}, 1000)