当前位置:首页 > VUE

自定义实现vue

2026-01-21 16:01:49VUE

自定义实现 Vue 的核心原理

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

数据响应式系统

通过 Object.definePropertyProxy 实现数据劫持,在属性被访问或修改时触发更新。

自定义实现vue

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(观察者)模式:

自定义实现vue

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 实现全文检索的方法 客户端全文检索(适用于小型数据集) 使用 flexsearch 或 lunr.js 等轻量级库实现前端全文检索: import FlexSearch from 'fle…

vue实现继承语法糖

vue实现继承语法糖

在Vue中实现继承可以通过多种方式模拟类继承的效果,以下是常见的几种方法: 使用mixins实现逻辑复用 通过Vue的mixins机制共享组件选项,达到类似继承的效果: const BaseC…

vue穿梭框组件实现

vue穿梭框组件实现

实现基础穿梭框组件 在Vue中实现穿梭框组件,可以使用<el-transfer>(Element UI)或手动实现。以下是手动实现的核心逻辑: <template> &…

vue原型实现

vue原型实现

Vue 原型实现的关键点 Vue.js 的原型系统是其响应式机制的核心部分,通过原型链实现数据的动态绑定和依赖收集。以下是实现 Vue 原型的主要技术要点。 数据响应式原理 Vue 通过 Obje…

vue实现app

vue实现app

Vue 实现 App 的常见方法 使用 Vue 开发移动端 App 主要有两种主流方案:混合开发(Hybrid)和原生渲染。以下是具体实现方式和工具链: 混合开发方案(WebView 嵌入) 通…

vue element实现

vue element实现

Vue Element UI 实现 Vue Element UI 是基于 Vue.js 的组件库,提供丰富的 UI 组件,适合快速开发企业级中后台产品。以下是一些关键实现方法和步骤: 安装 Vue…