当前位置:首页 > VUE

实现 vue 框架

2026-01-12 18:45:26VUE

实现 Vue 框架的核心思路

Vue 框架的核心功能包括响应式数据绑定、虚拟 DOM 渲染、组件系统等。以下是实现简化版 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)
    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)
      }
    })
  }

  compileText(node) {
    this.update(node, RegExp.$1, 'text')
  }

  update(node, exp, dir) {
    const updaterFn = updater[dir + 'Updater']
    updaterFn && updaterFn(node, this.$vm[exp])
    new Watcher(this.$vm, exp, function(value) {
      updaterFn && updaterFn(node, value)
    })
  }

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

  isDirective(attr) {
    return attr.indexOf('v-') === 0
  }
}

const updater = {
  textUpdater(node, value) {
    node.textContent = value
  },
  modelUpdater(node, value) {
    node.value = 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)
    this.proxyData(this.$data)
    new Compiler(options.el, this)
  }

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

使用方法

<div id="app">
  <p>{{ message }}</p>
  <input v-model="message">
</div>

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

这个简化实现包含了 Vue 的核心功能:数据响应式、模板编译、依赖收集和更新。实际 Vue 源码更加复杂,包含虚拟 DOM diff、组件生命周期、指令系统等更多功能。

实现 vue 框架

标签: 框架vue
分享给朋友:

相关文章

vue实现modal

vue实现modal

Vue 实现 Modal 弹窗组件 使用 Vue 实现 Modal 弹窗组件可以通过多种方式,包括原生 Vue 组件、第三方库或自定义指令。以下是几种常见方法: 原生 Vue 组件实现 创建一个基础…

vue课程实现

vue课程实现

Vue 课程实现方案 课程内容设计 Vue课程应从基础到高级逐步展开,涵盖Vue核心概念、组件化开发、状态管理、路由、构建工具等。基础部分包括Vue实例、模板语法、计算属性和侦听器。中级部分深入组件通…

vue键盘实现

vue键盘实现

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

vue 实现ztree

vue 实现ztree

在Vue中实现类似ZTree的功能,可以通过集成第三方库或自定义组件完成。以下是两种常见方法: 使用vue-tree组件 vue-tree是一个轻量级的Vue树形组件,支持复选框、懒加载等功能,适合…

vue实现刷新

vue实现刷新

Vue 实现页面刷新的方法 在Vue中实现页面刷新可以通过多种方式,以下是几种常见的方法: 使用 window.location.reload() 通过调用浏览器的原生方法强制刷新当前页面:…

vue前端实现

vue前端实现

Vue 前端实现基础步骤 安装 Vue.js 和相关依赖 通过 npm 或 yarn 安装 Vue.js,建议使用 Vue CLI 快速搭建项目。运行命令 npm install -g @vue/cl…