当前位置:首页 > 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实现多层评论回复

vue实现多层评论回复

Vue 实现多层评论回复 数据结构设计 多层评论通常采用嵌套结构,每个评论对象包含子评论数组。示例数据结构如下: comments: [ { id: 1, content: '父…

vue datepicker 实现

vue datepicker 实现

实现 Vue Datepicker 的基本方法 在 Vue 项目中实现日期选择功能,可以使用第三方库如 vue-datepicker 或 v-calendar。以下是两种常见实现方式: 安装 vue…

vue 实现递归

vue 实现递归

Vue 实现递归组件的方法 在 Vue 中实现递归组件通常用于处理树形结构数据,例如菜单、评论列表或文件目录。以下是实现递归组件的关键步骤: 定义递归组件 递归组件需要设置 name 属性,以便在模…

vue滚动实现

vue滚动实现

Vue 滚动实现方法 使用原生滚动 在 Vue 中可以通过 ref 获取 DOM 元素,调用原生滚动方法实现滚动效果。适用于简单场景。 <template> <div ref=…

vue监听实现

vue监听实现

Vue 监听实现方法 在 Vue 中可以通过多种方式实现监听数据变化或事件触发,以下是常见的几种方法: 使用 watch 选项 watch 是 Vue 提供的核心功能之一,用于观察和响应 Vue 实…

vue分页实现

vue分页实现

实现Vue分页的几种方法 使用Element UI的分页组件 安装Element UI库后,可以直接使用其分页组件。以下是一个基本示例: <template> <div>…