当前位置:首页 > VUE

自实现vue

2026-03-07 11:48:26VUE

自实现 Vue 的核心思路

实现一个简化版 Vue 需要理解其核心机制:数据响应式、模板编译、虚拟 DOM 和组件系统。以下是关键步骤:

数据响应式系统

通过 Object.definePropertyProxy 实现数据劫持。当数据变化时通知依赖的视图更新。

class Observer {
  constructor(data) {
    this.walk(data)
  }
  walk(data) {
    if (!data || typeof data !== 'object') return
    Object.keys(data).forEach(key => {
      this.defineReactive(data, key, data[key])
    })
  }
  defineReactive(obj, key, val) {
    const dep = new Dep()
    this.walk(val)
    Object.defineProperty(obj, key, {
      enumerable: true,
      configurable: true,
      get() {
        Dep.target && dep.addSub(Dep.target)
        return val
      },
      set(newVal) {
        if (newVal === val) return
        val = newVal
        dep.notify()
      }
    })
  }
}

依赖收集系统

实现 DepWatcher 类管理依赖关系。

class Dep {
  constructor() {
    this.subs = []
  }
  addSub(sub) {
    this.subs.push(sub)
  }
  notify() {
    this.subs.forEach(sub => sub.update())
  }
}

class Watcher {
  constructor(vm, key, cb) {
    this.vm = vm
    this.key = key
    this.cb = cb
    Dep.target = this
    this.oldValue = vm[key]
    Dep.target = null
  }
  update() {
    const newValue = this.vm[this.key]
    if (newValue === this.oldValue) return
    this.cb(newValue)
    this.oldValue = newValue
  }
}

模板编译

实现简单模板解析,将模板转换为渲染函数。

class Compiler {
  constructor(el, vm) {
    this.$vm = vm
    this.$el = document.querySelector(el)
    this.compile(this.$el)
  }
  compile(node) {
    const childNodes = node.childNodes
    Array.from(childNodes).forEach(child => {
      if (this.isElement(child)) {
        this.compileElement(child)
      } else if (this.isInterpolation(child)) {
        this.compileText(child)
      }
      if (child.childNodes && child.childNodes.length > 0) {
        this.compile(child)
      }
    })
  }
  isElement(node) {
    return node.nodeType === 1
  }
  isInterpolation(node) {
    return node.nodeType === 3 && /\{\{(.*)\}\}/.test(node.textContent)
  }
  compileText(node) {
    const exp = RegExp.$1.trim()
    this.update(node, exp, 'text')
  }
  compileElement(node) {
    const attributes = node.attributes
    Array.from(attributes).forEach(attr => {
      const attrName = attr.name
      const exp = attr.value
      if (this.isDirective(attrName)) {
        const dir = attrName.substring(2)
        this[dir] && this[dir](node, exp)
      }
    })
  }
  isDirective(attr) {
    return attr.startsWith('v-')
  }
  text(node, exp) {
    this.update(node, exp, 'text')
  }
  html(node, exp) {
    this.update(node, exp, 'html')
  }
  update(node, exp, dir) {
    const fn = this[dir + 'Updater']
    fn && fn(node, this.$vm[exp])
    new Watcher(this.$vm, exp, val => {
      fn && fn(node, val)
    })
  }
  textUpdater(node, value) {
    node.textContent = value
  }
  htmlUpdater(node, value) {
    node.innerHTML = value
  }
}

Vue 类实现

整合各模块实现基础 Vue 类。

自实现vue

class Vue {
  constructor(options) {
    this.$options = options
    this.$data = options.data
    new Observer(this.$data)
    Object.keys(this.$data).forEach(key => {
      this.proxyData(key)
    })
    new Compiler(options.el, this)
  }
  proxyData(key) {
    Object.defineProperty(this, key, {
      get() {
        return this.$data[key]
      },
      set(newVal) {
        this.$data[key] = newVal
      }
    })
  }
}

使用方法示例

<div id="app">
  <p>{{ message }}</p>
  <button v-text="btnText"></button>
</div>

<script>
const app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue',
    btnText: 'Click me'
  }
})
</script>

实现要点说明

数据劫持通过 Object.defineProperty 实现,现代 Vue 3 使用 Proxy 有更好性能 依赖收集系统确保数据变化时能精准更新相关视图 模板编译器将模板转换为可执行的渲染逻辑 通过代理将 data 的属性挂载到 Vue 实例上方便访问

标签: vue
分享给朋友:

相关文章

vue tab实现

vue tab实现

Vue Tab 实现方法 使用动态组件实现 Tab 在 Vue 中可以通过动态组件 <component :is="currentTab"> 结合 v-for 和 v-bind 实现 Ta…

vue实现计算

vue实现计算

Vue 实现计算的方法 在 Vue 中实现计算功能可以通过多种方式完成,主要包括计算属性(computed)、方法(methods)和侦听器(watch)。以下是具体的实现方法: 计算属性(Comp…

vue 实现fadeout

vue 实现fadeout

Vue 实现淡出效果 在 Vue 中实现淡出(fade-out)效果可以通过 CSS 过渡或动画结合 Vue 的动态渲染功能完成。以下是几种常见方法: 使用 Vue 过渡(Transition)组件…

vue实现computed

vue实现computed

Vue 中 computed 的实现原理 computed 属性是 Vue 的一个核心特性,它基于响应式依赖进行缓存,仅在依赖发生变化时重新计算。以下是 computed 的实现方式: 基本用法 在…

vue实现树形

vue实现树形

Vue 实现树形组件 在 Vue 中实现树形结构通常需要递归组件和动态数据绑定。以下是实现树形组件的几种常见方法。 递归组件实现 递归组件是 Vue 中实现树形结构的核心方法。通过组件调用自身,可以…

vue实现拖拉

vue实现拖拉

实现拖拽功能的基本步骤 在Vue中实现拖拽功能可以通过原生HTML5的拖放API或第三方库如vuedraggable完成。以下是两种方法的详细说明。 使用HTML5原生拖放API HTML5提供了原…