当前位置:首页 > VUE

实现 vue 框架

2026-01-12 18:45:26VUE

实现 Vue 框架的核心思路

Vue 框架的核心功能包括响应式数据绑定、虚拟 DOM 渲染、组件系统等。以下是实现简化版 Vue 框架的关键步骤:

响应式数据系统

通过 Object.definePropertyProxy 实现数据劫持,监听数据变化并触发更新:

实现 vue 框架

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

编译器实现

将模板编译为渲染函数:

实现 vue 框架

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 路由实现

Vue 路由实现方法 安装 Vue Router 使用 npm 或 yarn 安装 Vue Router 依赖包: npm install vue-router # 或 yarn add vue-r…

vue实现好友列表

vue实现好友列表

实现好友列表的Vue组件 数据准备 在Vue组件的data中定义好友列表数据,通常是一个数组对象,每个对象包含好友的基本信息如ID、头像、昵称等。 data() { return {…

vue实现适老化样式

vue实现适老化样式

Vue 实现适老化样式的关键方法 全局字体与字号调整 通过 CSS 变量或主题配置统一放大基础字号,建议正文不小于 18px,标题更大。在 App.vue 中设置全局样式: :root { --…

vue登录业务的实现

vue登录业务的实现

实现登录业务的基本流程 在Vue中实现登录业务通常涉及前端界面设计、表单验证、API请求交互、状态管理以及路由控制等环节。以下是核心实现步骤: 登录表单设计与验证 创建包含用户名和密码输入框的登录组…

vue使用vr实现标注

vue使用vr实现标注

Vue 中使用 VR 实现标注的方法 在 Vue 项目中结合 VR 技术实现标注功能,可以通过 WebXR 和 Three.js 等库实现。以下为具体实现方法: 安装依赖 确保项目中已安装 Thre…

vue穿梭框组件实现

vue穿梭框组件实现

实现基础穿梭框组件 在Vue中实现穿梭框组件,可以使用<el-transfer>(Element UI)或手动实现。以下是手动实现的核心逻辑: <template> &l…