当前位置:首页 > VUE

简易实现vue

2026-01-06 23:53:34VUE

简易实现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) {
    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 实现倒计时的基本方法 使用 setInterval 和响应式数据 在 Vue 组件中定义一个响应式变量(如 countdown),通过 setInterval 每秒更新数值。组件销毁时清除定…

vue实现目录

vue实现目录

Vue 实现目录功能 在 Vue 中实现目录功能通常需要动态生成目录结构,并支持点击跳转到对应内容区域。以下是几种常见实现方式: 基于滚动监听和动态生成 安装依赖(如需): npm install…

vue怎么实现动画

vue怎么实现动画

Vue 动画实现方法 Vue 提供了多种方式实现动画效果,包括内置过渡系统、第三方库集成以及 CSS 动画。以下是常见实现方法: 使用 Vue 过渡系统 通过 <transition>…

拖拽式编程vue实现

拖拽式编程vue实现

拖拽式编程在 Vue 中的实现方法 使用 HTML5 原生拖放 API Vue 可以结合 HTML5 的拖放 API 实现基础拖拽功能。通过 draggable 属性标记可拖拽元素,监听 dragst…

vue如何实现到期提醒

vue如何实现到期提醒

实现 Vue 到期提醒功能 使用计算属性计算剩余时间 在 Vue 组件中定义一个计算属性,计算目标日期与当前日期的差值。通过 Date 对象获取时间戳并计算剩余天数或小时数。 computed:…

vue设计与实现下载

vue设计与实现下载

vue设计与实现电子书下载 《Vue.js设计与实现》是一本深入解析Vue.js框架原理的书籍,由霍春阳(HcySunYang)撰写。以下是获取该资源的常见途径: 正版购买渠道 京东、当当、天…