当前位置:首页 > 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 实现头像裁剪功能 实现头像裁剪功能通常需要结合第三方库如 cropperjs 或 vue-cropper。以下是两种常见实现方式: 使用 vue-cropper 库 安装依赖: npm i…

vue调用接口实现退出

vue调用接口实现退出

实现Vue退出功能的步骤 在Vue中调用接口实现退出功能通常需要与后端API交互,以下是实现方法: 前端实现 创建退出方法,调用后端API接口: methods: { logout()…

vue 实现菜单

vue 实现菜单

Vue 实现菜单的方法 使用 Vue 实现菜单可以通过多种方式,以下是几种常见的方法: 使用 Vue Router 实现动态路由菜单 通过 Vue Router 可以动态生成菜单,根据路由配置自动渲…

vue实现公式

vue实现公式

在Vue中实现公式展示或计算可以通过多种方式实现,以下为具体方法: 使用模板插值与计算属性 若公式较简单,可直接在模板中使用插值表达式或计算属性。例如计算圆的面积: <templat…

vue实现toast

vue实现toast

Vue 实现 Toast 的方法 使用第三方库(推荐) 对于快速实现 Toast 功能,推荐使用成熟的第三方库如 vue-toastification 或 vant 的 Toast 组件。 安装 v…

实现vue datepicker

实现vue datepicker

安装依赖 使用 vue-datepicker 或第三方库如 v-calendar 或 vue2-datepicker。以 vue2-datepicker 为例: npm install vue2…