当前位置:首页 > VUE

简易实现vue

2026-01-06 23:53:34VUE

简易 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) {
    this.walk(val) // 递归处理嵌套对象
    const dep = new Dep()
    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)
  }

  compileElement(node) {
    const attrs = node.attributes
    Array.from(attrs).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')
  }

  model(node, exp) {
    this.update(node, exp, 'model')
    node.addEventListener('input', e => {
      this.$vm[exp] = e.target.value
    })
  }

  update(node, exp, dir) {
    const fn = this[dir + 'Updater']
    fn && fn(node, this.$vm[exp])

    new Watcher(this.$vm, exp, value => {
      fn && fn(node, value)
    })
  }

  textUpdater(node, value) {
    node.textContent = value
  }

  modelUpdater(node, value) {
    node.value = value
  }

  compileText(node) {
    const exp = RegExp.$1.trim()
    this.update(node, exp, 'text')
  }
}

观察者实现

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)
    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>
  <input v-model="message">
</div>

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

这个实现包含了 Vue 的核心功能:数据响应式、模板编译、指令处理。实际 Vue 源码更复杂,包含虚拟 DOM、组件系统等高级特性,但以上代码演示了最核心的响应式原理。

简易实现vue

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

相关文章

vue如何实现注册

vue如何实现注册

实现用户注册功能 在Vue中实现注册功能通常需要结合前端表单和后端API交互。以下是完整的实现方案: 创建注册表单组件 注册表单需要包含用户名、邮箱、密码等基本字段,并进行表单验证: <…

vue实现菜单调用

vue实现菜单调用

Vue 实现动态菜单的常见方法 基于路由配置生成菜单 Vue Router 的路由配置可以天然转化为菜单结构,适合权限与路由绑定的系统: // router/index.js const route…

vue为啥能实现监听

vue为啥能实现监听

Vue 实现监听的原理 Vue 的监听能力主要基于其响应式系统,该系统通过数据劫持和依赖收集实现。当数据变化时,系统能自动触发视图更新或执行回调函数。 核心机制:Object.defineProp…

前端多线程实现vue

前端多线程实现vue

前端多线程与Vue的结合 在Vue中实现多线程通常通过Web Worker技术完成。Web Worker允许在后台线程中运行脚本,避免阻塞主线程,适合处理计算密集型任务。 使用Web Worker的…

vue怎么实现数据检测

vue怎么实现数据检测

Vue 数据检测的实现方式 Vue 通过响应式系统实现数据检测,核心机制基于 Object.defineProperty(Vue 2)或 Proxy(Vue 3)。以下是具体实现方法: 基于 Vu…

vue实现滚动截屏

vue实现滚动截屏

实现滚动截屏的基本思路 滚动截屏通常指对超出可视区域的长页面进行完整截图。在Vue中,可以通过结合DOM操作、Canvas绘制及第三方库实现。以下是具体方法: 使用html2canvas库实现…