← 返回完整题库
vue.js困难

手写 vue 的双向绑定

参考答案

目标

Observer 把 data 变 getter/setter,Dep 收集/通知,Watcher 订阅并更新视图,Compile 解析指令与插值。

class Dep {
  constructor() { this.subs = [] }
  addSub(w) { this.subs.push(w) }
  depend() { if (Dep.target) this.addSub(Dep.target) }
  notify() { this.subs.forEach(w => w.update()) }
}

function observe(obj) {
  if (!obj || typeof obj !== 'object') return
  Object.keys(obj).forEach(k => defineReactive(obj, k, obj[k]))
}
function defineReactive(obj, key, val) {
  observe(val)
  const dep = new Dep()
  Object.defineProperty(obj, key, {
    get() { dep.depend(); return val },
    set(nv) { if (nv === val) return; val = nv; dep.notify() },
  })
}

class Watcher {
  constructor(vm, exp, cb) { this.vm = vm; this.exp = exp; this.cb = cb; this.get() }
  get() {
    Dep.target = this
    const v = this.vm[this.exp]
    Dep.target = null
    return v
  }
  update() { this.cb.call(this.vm, this.vm[this.exp]) }
}

function compile(node, vm) {
  if (node.nodeType === 3) {
    const m = node.textContent.match(/{{(.+?)}}/g)
    if (m) {
      const exp = RegExp.$1.trim()
      new Watcher(vm, exp, v => { node.textContent = v })
    }
  }
  if (node.nodeType === 1) {
    const attr = node.getAttribute('v-model')
    if (attr) {
      node.addEventListener('input', e => { vm[attr] = e.target.value })
      new Watcher(vm, attr, v => { node.value = v })
      node.value = vm[attr]
    }
  }
  node.childNodes.forEach(c => compile(c, vm))
}

class Vue {
  constructor(options) {
    this.$data = options.data
    observe(this.$data)
    Object.keys(this.$data).forEach(k => Object.defineProperty(this, k, {
      get: () => this.$data[k], set: v => { this.$data[k] = v },
    }))
    compile(options.el, this)
  }
}

关键点

  1. 依赖收集必须在 getter 里,且要知道当前是谁在读——用全局 Dep.target(Vue 2 即 Dep.target)。
  2. setter 里 notify,初始化时递归 observe 嵌套。
  3. 编译期建 watcher,每个插值/指令一个,get() 读一次完成收集。
  4. 生产级 Vue 2 还需补:nextTick 批量异步更新(queue)、数组 7 方法重写、$set/$delete、computed 的 dirty 缓存、vnode diff。面试要主动补这几项,否则只是玩具。

Vue 3 对应:defineReactive → Proxy + Reflect,Dep/Watcher → WeakMap + effect/scheduler。

本题来自 计算机知识面试题库,共 921 道题。