当前位置:首页 > VUE

自定义实现vue

2026-01-21 16:01:49VUE

自定义实现 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()
      }
    })
  }
}

依赖收集与发布订阅

实现 Dep(依赖收集器)和 Watcher(观察者)模式:

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 attrs = node.attributes
    Array.from(attrs).forEach(attr => {
      if (this.isDirective(attr.name)) {
        const dir = attr.name.substring(2)
        this[dir] && this[dir](node, attr.value)
      }
    })
  }

  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 updater = this[`${dir}Updater`]
    updater && updater(node, this.$vm[exp])
    new Watcher(this.$vm, exp, value => {
      updater && updater(node, value)
    })
  }

  textUpdater(node, value) {
    node.textContent = value
  }

  htmlUpdater(node, value) {
    node.innerHTML = value
  }
}

整合实现

创建 Vue 类整合以上功能:

class Vue {
  constructor(options) {
    this.$options = options
    this.$data = options.data
    new Observer(this.$data)
    this.proxyData(this.$data)
    new Compiler(options.el, this)
  }

  proxyData(data) {
    Object.keys(data).forEach(key => {
      Object.defineProperty(this, key, {
        get() {
          return data[key]
        },
        set(newVal) {
          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>

实现注意事项

  • 现代 Vue 3 使用 Proxy 替代 Object.defineProperty 实现响应式
  • 真实实现需要考虑更多边界条件和性能优化
  • 虚拟 DOM diff 算法是性能关键
  • 组件系统需要额外实现插槽、生命周期等机制

这个简化实现展示了 Vue 的核心原理,真实框架需要处理更多复杂场景和优化。

自定义实现vue

标签: 自定义vue
分享给朋友:

相关文章

vue实现静态查询

vue实现静态查询

Vue 实现静态查询 在 Vue 中实现静态查询通常指不依赖后端接口,直接在前端处理数据筛选或搜索功能。以下是几种常见实现方式: 使用计算属性过滤数据 通过计算属性对静态数据进行筛选,适合简单查询场…

vue实现购物按钮

vue实现购物按钮

Vue 购物按钮实现方法 基础按钮实现 使用 Vue 的模板语法创建基础按钮组件,绑定点击事件处理购物逻辑: <template> <button @click="addTo…

vue实现好评弹框

vue实现好评弹框

Vue 实现好评弹框的方法 使用 Vue 实现好评弹框可以通过组件化方式完成,结合动态数据绑定和事件处理。以下是具体实现步骤: 1. 创建弹框组件 新建一个 RatingDialog.vue…

vue实现页面截屏

vue实现页面截屏

使用html2canvas库实现截屏 html2canvas是一个流行的JavaScript库,可以将DOM元素转换为Canvas图像。在Vue项目中安装html2canvas: npm insta…

vue实现列表显示

vue实现列表显示

Vue 实现列表显示的方法 在 Vue 中实现列表显示通常使用 v-for 指令,结合数组或对象数据渲染动态列表。以下是几种常见的实现方式。 基本列表渲染 通过 v-for 指令遍历数组,动态生成…

vue的艾特功能实现

vue的艾特功能实现

Vue 的 @ 功能实现 在 Vue 中实现类似社交平台的 @ 功能,通常涉及输入框的监听、用户匹配和选择插入。以下是具体实现方法: 监听输入框内容 使用 v-model 绑定输入框内容,并通过…