当前位置:首页 > VUE

实现简易vue

2026-02-10 02:05:41VUE

实现简易 Vue 的核心思路

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

数据响应式系统

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

依赖收集系统

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

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

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

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

Dep.target = null

编译器实现

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

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 类:

实现简易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.js 的核心原理基于响应式系统、虚拟 DOM 和模板编译。以下是其核心实现机制的分解: 响应式系统 Vue 使用 Object.defineProperty(Vu…

vue实现radio

vue实现radio

Vue 实现 Radio 按钮 在 Vue 中实现 Radio 按钮可以通过 v-model 进行数据绑定,结合 input 元素的 type="radio" 属性。以下是一个基本示例: <t…

vue首页实现

vue首页实现

实现Vue首页的基本步骤 创建一个Vue首页通常涉及项目初始化、页面结构设计、路由配置和组件开发。以下是具体实现方法: 初始化Vue项目 使用Vue CLI或Vite快速搭建项目结构: npm i…

vue 实现图钉

vue 实现图钉

实现图钉效果的步骤 在Vue中实现图钉(固定位置)效果,可以通过CSS的position: sticky属性或监听滚动事件动态修改元素样式。以下是两种常见方法: 方法一:使用CSS的position…

vue删除实现

vue删除实现

Vue 删除功能的实现方法 在 Vue 中实现删除功能通常涉及以下几个步骤: 方法一:使用数组的 splice 方法 通过索引删除数组中的元素,适用于列表渲染的场景。 methods: {…

vue实现文章滚动

vue实现文章滚动

Vue 实现文章滚动效果 使用 CSS 实现基础滚动 通过 CSS 的 overflow 和 height 属性控制滚动区域,适用于静态内容滚动。在 Vue 模板中定义固定高度的容器,内容超出后自动滚…