当前位置:首页 > VUE

从零开始实现vue

2026-01-23 15:10:19VUE

从零实现 Vue.js 的核心功能

Vue.js 的核心功能包括数据响应式、虚拟 DOM、模板编译等。以下是一个简化版的实现思路:

数据响应式系统

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

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

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

观察者

实现 Watcher 来连接响应式系统和视图更新。

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)
    this.proxy(this.$data)
    new Compiler(options.el, this)
  }

  proxy(data) {
    Object.keys(data).forEach(key => {
      Object.defineProperty(this, key, {
        get() {
          return data[key]
        },
        set(newVal) {
          data[key] = newVal
        }
      })
    })
  }
}

使用方法

创建一个简单的 Vue 实例:

<div id="app">
  {{ message }}
  <div v-text="message"></div>
</div>

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

实现要点

  1. 数据响应式:通过 Object.defineProperty 或 Proxy 拦截数据访问和修改
  2. 依赖收集:在 getter 中收集依赖,在 setter 中触发更新
  3. 模板编译:将模板转换为渲染函数,解析指令和插值表达式
  4. 虚拟 DOM:可以进一步实现虚拟 DOM 和 diff 算法提高性能

这个简化实现包含了 Vue 的核心功能,实际 Vue 源码更加复杂,包含组件系统、生命周期、指令系统等更多功能。

从零开始实现vue

标签: 从零开始vue
分享给朋友:

相关文章

vue实现微博发布动态

vue实现微博发布动态

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

vue slot实现

vue slot实现

vue slot 的实现方法 在 Vue 中,slot 是一种内容分发机制,允许父组件向子组件传递模板内容。以下是几种常见的 slot 实现方式: 默认 slot 默认 slot 是最基础的 slo…

vue实现tree

vue实现tree

Vue 实现 Tree 组件 使用 Vue 实现 Tree 组件可以通过递归组件的方式来实现层级结构展示。以下是一个完整的实现方法: 基础递归组件实现 创建 Tree 组件文件 Tree.vue,…

vue filter 实现

vue filter 实现

在 Vue.js 中,过滤器(Filter)是一种用于文本格式化的功能,可以在模板中直接使用。以下是实现过滤器的详细方法: 全局过滤器注册 通过 Vue.filter 方法注册全局过滤器,可在所有…

vue键盘实现

vue键盘实现

监听键盘事件 在Vue中监听键盘事件可以通过v-on指令或@缩写实现。常见的键盘事件包括keydown、keyup和keypress。例如监听回车键事件: <template> &…

vue 实现折叠

vue 实现折叠

Vue 实现折叠功能的方法 在 Vue 中实现折叠功能可以通过多种方式完成,以下是几种常见的实现方法: 使用 v-if 或 v-show 控制显示隐藏 通过绑定一个布尔值变量,结合 v-if 或 v…