当前位置:首页 > VUE

简易实现vue

2026-02-09 10:19:34VUE

简易 Vue 实现核心思路

创建一个极简的 Vue 实现需要理解其核心机制:数据响应式、模板编译和虚拟 DOM。以下是一个简化版实现框架,仅包含核心功能。

数据响应式系统

通过 Object.defineProperty 实现数据劫持,这是 Vue 2.x 的响应式原理基础:

class Observer {
  constructor(data) {
    this.walk(data)
  }

  walk(data) {
    Object.keys(data).forEach(key => {
      this.defineReactive(data, key, data[key])
    })
  }

  defineReactive(obj, key, val) {
    const dep = new Dep()
    Object.defineProperty(obj, key, {
      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

编译模板

实现最基础的模板编译功能,将 {{}} 语法转换为数据绑定:

function compile(el, vm) {
  vm.$el = document.querySelector(el)
  const fragment = document.createDocumentFragment()
  let child
  while (child = vm.$el.firstChild) {
    fragment.appendChild(child)
  }

  function replace(frag) {
    Array.from(frag.childNodes).forEach(node => {
      const txt = node.textContent
      const reg = /\{\{(.*?)\}\}/g

      if (node.nodeType === 3 && reg.test(txt)) {
        const arr = RegExp.$1.split('.')
        let val = vm
        arr.forEach(key => {
          val = val[key]
        })
        node.textContent = txt.replace(reg, val).trim()

        new Watcher(vm, RegExp.$1, newVal => {
          node.textContent = txt.replace(reg, newVal).trim()
        })
      }

      if (node.childNodes && node.childNodes.length) {
        replace(node)
      }
    })
  }

  replace(fragment)
  vm.$el.appendChild(fragment)
}

观察者实现

创建 Watcher 类来连接响应式数据和视图更新:

class Watcher {
  constructor(vm, exp, cb) {
    this.vm = vm
    this.exp = exp
    this.cb = cb
    Dep.target = this
    let val = vm
    exp.split('.').forEach(key => {
      val = val[key]
    })
    Dep.target = null
  }

  update() {
    let val = this.vm
    this.exp.split('.').forEach(key => {
      val = val[key]
    })
    this.cb(val)
  }
}

主类实现

组合以上功能创建 MiniVue 类:

class MiniVue {
  constructor(options) {
    this.$options = options
    this._data = options.data
    new Observer(this._data)
    Object.keys(this._data).forEach(key => {
      this._proxy(key)
    })
    compile(options.el, this)
  }

  _proxy(key) {
    Object.defineProperty(this, key, {
      configurable: true,
      enumerable: true,
      get: () => this._data[key],
      set: val => {
        this._data[key] = val
      }
    })
  }
}

使用示例

这样实现的简易 Vue 可以这样使用:

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

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

这个实现包含了 Vue 最核心的响应式系统、模板编译和依赖收集机制。实际 Vue 源码还包含虚拟 DOM diff、组件系统等更多复杂功能,但这个简化版已经展示了核心原理。

简易实现vue

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

相关文章

vue实现微博发布动态

vue实现微博发布动态

使用Vue实现微博发布动态功能 创建Vue组件结构 新建一个WeiboPost.vue组件,包含文本框、图片上传和发布按钮: <template> <div class="we…

vue交互实现

vue交互实现

Vue 交互实现方法 Vue.js 提供了多种方式实现用户交互,包括事件处理、表单绑定、动态渲染等。以下是常见的交互实现方法: 事件处理 通过 v-on 或 @ 指令绑定事件,触发方法或直接执行表达…

vue  实现tab

vue 实现tab

实现 Tab 切换功能 在 Vue 中实现 Tab 切换功能可以通过动态组件或条件渲染完成。以下是两种常见方法: 使用 v-if 或 v-show 实现条件渲染 通过绑定 currentTab 变量…

vue实现ssr

vue实现ssr

Vue 实现 SSR(服务端渲染) Vue 的服务端渲染(SSR)允许在服务器端生成完整的 HTML 内容,再发送到客户端,提升首屏加载速度和 SEO 友好性。以下是实现 Vue SSR 的关键步骤和…

vue实现答题

vue实现答题

Vue 实现答题功能 数据结构设计 使用 Vue 的响应式特性管理题目和答案数据。通常需要以下数据结构: data() { return { questions: [ {…

vue实现评分

vue实现评分

Vue 实现评分功能 使用组件库实现 安装 element-ui 或 ant-design-vue 这类 UI 库,它们已经内置了评分组件。 以 element-ui 为例: <temp…