当前位置:首页 > VUE

实现简易vue

2026-02-10 02:05:41VUE

实现简易 Vue 的核心思路

简易 Vue 的实现主要围绕数据响应式、模板编译和依赖收集展开。以下是一个简化版 Vue 的实现框架:

数据响应式系统

通过 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()
      }
    })
  }
}

依赖收集系统

实现简单的发布-订阅模式:

class Dep {
  constructor() {
    this.subs = []
  }

  addSub(sub) {
    this.subs.push(sub)
  }

  notify() {
    this.subs.forEach(sub => sub.update())
  }
}

Dep.target = null

编译器实现

简单模板编译,将模板中的插值表达式替换为数据:

实现简易vue

class Compiler {
  constructor(el, vm) {
    this.$vm = vm
    this.$el = document.querySelector(el)

    if (this.$el) {
      this.compile(this.$el)
    }
  }

  compile(el) {
    const childNodes = el.childNodes
    Array.from(childNodes).forEach(node => {
      if (this.isElement(node)) {
        this.compileElement(node)
      } else if (this.isInterpolation(node)) {
        this.compileText(node)
      }

      if (node.childNodes && node.childNodes.length > 0) {
        this.compile(node)
      }
    })
  }

  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')
  }

  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
  }
}

观察者实现

连接响应式数据和视图更新的桥梁:

class Watcher {
  constructor(vm, key, cb) {
    this.vm = vm
    this.key = key
    this.cb = cb

    Dep.target = this
    this.vm[this.key] // 触发getter,收集依赖
    Dep.target = null
  }

  update() {
    this.cb.call(this.vm, this.vm[this.key])
  }
}

主框架整合

将各个模块组合成简易 Vue 类:

class Vue {
  constructor(options) {
    this.$options = options
    this.$data = options.data

    // 数据响应式
    new Observer(this.$data)

    // 代理data到Vue实例
    Object.keys(this.$data).forEach(key => {
      this._proxy(key)
    })

    // 编译模板
    new Compiler(options.el, this)
  }

  _proxy(key) {
    Object.defineProperty(this, key, {
      get() {
        return this.$data[key]
      },
      set(newVal) {
        this.$data[key] = newVal
      }
    })
  }
}

使用示例

<div id="app">
  <p>{{ message }}</p>
</div>

<script>
  const vm = new Vue({
    el: '#app',
    data: {
      message: 'Hello Mini Vue!'
    }
  })

  setTimeout(() => {
    vm.message = 'Data changed!'
  }, 1000)
</script>

这个简易实现包含了 Vue 最核心的响应式系统、模板编译和依赖收集机制。实际 Vue 的实现要复杂得多,包括虚拟 DOM、组件系统、指令系统等更多功能。

标签: 简易vue
分享给朋友:

相关文章

vue实现活动倒计时

vue实现活动倒计时

实现活动倒计时的基本思路 在Vue中实现活动倒计时通常需要获取当前时间与活动结束时间的差值,并将其转换为天、小时、分钟、秒的格式展示。通过定时器每秒更新显示的时间。 定义倒计时数据 在Vue组件的…

vue实现帖子

vue实现帖子

Vue 实现帖子功能 使用 Vue 实现帖子功能需要结合前端框架和后端数据交互,以下是实现的关键步骤和代码示例。 帖子列表展示 创建帖子列表组件,使用 v-for 渲染帖子数据,通过 axios…

vue实现tablegrid

vue实现tablegrid

Vue 实现 TableGrid 的方法 使用 Element UI 的 Table 组件 Element UI 提供了强大的 Table 组件,可以快速实现表格布局。安装 Element UI 后,…

vue computed 实现

vue computed 实现

computed 的基本用法 在 Vue 中,computed 用于声明计算属性,这些属性基于响应式依赖进行缓存。只有当依赖发生变化时,计算属性才会重新计算。 new Vue({ data:…

vue实现socket

vue实现socket

Vue 中实现 WebSocket 通信 在 Vue 项目中实现 WebSocket 通信可以通过原生 WebSocket API 或第三方库(如 socket.io-client)完成。以下是两种常…

vue vnode实现

vue vnode实现

Vue VNode 实现原理 VNode(Virtual Node)是 Vue 的核心概念之一,用于描述真实 DOM 的轻量级虚拟表示。VNode 的实现涉及以下关键点: VNode 的基本结构…