MVVM 双向数据绑定实现

手写一个简易的 MVVM 框架,实现数据与视图的双向绑定

问题

实现一个简易的 MVVM 框架,支持数据变化自动更新视图,视图变化自动更新数据。

解答

MVVM 双向绑定的实现需要三个部分:

  1. Observer:数据劫持,监听数据变化
  2. Compiler:编译模板,绑定更新函数
  3. Watcher:连接 Observer 和 Compiler 的桥梁

完整实现

// 依赖收集器
class Dep {
  constructor() {
    this.subs = []
  }

  addSub(watcher) {
    this.subs.push(watcher)
  }

  notify() {
    this.subs.forEach(watcher => watcher.update())
  }
}

// 全局变量,用于收集依赖
Dep.target = null

// 观察者
class Watcher {
  constructor(vm, key, callback) {
    this.vm = vm
    this.key = key
    this.callback = callback
    // 触发 getter,收集依赖
    this.value = this.get()
  }

  get() {
    Dep.target = this
    // 访问属性,触发 getter
    const value = this.vm[this.key]
    Dep.target = null
    return value
  }

  update() {
    const newValue = this.vm[this.key]
    if (newValue !== this.value) {
      this.value = newValue
      this.callback(newValue)
    }
  }
}

// 数据劫持
class Observer {
  constructor(data) {
    this.observe(data)
  }

  observe(data) {
    if (!data || typeof data !== 'object') return

    Object.keys(data).forEach(key => {
      this.defineReactive(data, key, data[key])
    })
  }

  defineReactive(obj, key, value) {
    // 递归观察子属性
    this.observe(value)

    const dep = new Dep()

    Object.defineProperty(obj, key, {
      enumerable: true,
      configurable: true,
      get() {
        // 收集依赖
        if (Dep.target) {
          dep.addSub(Dep.target)
        }
        return value
      },
      set: (newValue) => {
        if (newValue === value) return
        value = newValue
        // 新值也要观察
        this.observe(newValue)
        // 通知更新
        dep.notify()
      }
    })
  }
}

// 编译器
class Compiler {
  constructor(el, vm) {
    this.vm = vm
    this.el = document.querySelector(el)
    this.fragment = null
    this.init()
  }

  init() {
    this.fragment = this.createFragment(this.el)
    this.compile(this.fragment)
    this.el.appendChild(this.fragment)
  }

  createFragment(el) {
    const fragment = document.createDocumentFragment()
    let child
    while ((child = el.firstChild)) {
      fragment.appendChild(child)
    }
    return fragment
  }

  compile(node) {
    const childNodes = node.childNodes
    Array.from(childNodes).forEach(child => {
      if (child.nodeType === 1) {
        // 元素节点
        this.compileElement(child)
      } else if (child.nodeType === 3) {
        // 文本节点
        this.compileText(child)
      }

      if (child.childNodes && child.childNodes.length) {
        this.compile(child)
      }
    })
  }

  compileElement(node) {
    const attrs = node.attributes
    Array.from(attrs).forEach(attr => {
      const name = attr.name
      if (name.startsWith('v-')) {
        const directive = name.substring(2)
        const key = attr.value

        if (directive === 'model') {
          // v-model 双向绑定
          node.value = this.vm[key]

          // 视图 -> 数据
          node.addEventListener('input', (e) => {
            this.vm[key] = e.target.value
          })

          // 数据 -> 视图
          new Watcher(this.vm, key, (value) => {
            node.value = value
          })
        }
      }
    })
  }

  compileText(node) {
    const reg = /\{\{(.+?)\}\}/g
    const text = node.textContent

    if (reg.test(text)) {
      const key = RegExp.$1.trim()
      node.textContent = text.replace(reg, this.vm[key])

      new Watcher(this.vm, key, (value) => {
        node.textContent = text.replace(reg, value)
      })
    }
  }
}

// MVVM 入口
class MVVM {
  constructor(options) {
    this.$el = options.el
    this.$data = options.data

    // 代理 data,可以直接通过 vm.xxx 访问
    this.proxyData(this.$data)

    // 数据劫持
    new Observer(this.$data)

    // 编译模板
    new Compiler(this.$el, this)
  }

  proxyData(data) {
    Object.keys(data).forEach(key => {
      Object.defineProperty(this, key, {
        get() {
          return data[key]
        },
        set(newValue) {
          data[key] = newValue
        }
      })
    })
  }
}

使用示例

<div id="app">
  <input type="text" v-model="message">
  <p>{{ message }}</p>
</div>

<script>
const vm = new MVVM({
  el: '#app',
  data: {
    message: 'Hello MVVM'
  }
})

// 测试:修改数据,视图自动更新
setTimeout(() => {
  vm.message = '数据已更新'
}, 2000)
</script>

关键点

  • 数据劫持:使用 Object.defineProperty 拦截属性的读写操作
  • 依赖收集:在 getter 中收集 Watcher,在 setter 中触发更新
  • 发布订阅:Dep 作为调度中心,管理 Watcher 的添加和通知
  • 双向绑定:v-model 通过监听 input 事件实现视图到数据的同步
  • Vue 3 改进:使用 Proxy 替代 Object.defineProperty,可以监听数组变化和新增属性