当前位置:首页 > 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实现全文检索

vue实现全文检索

Vue 实现全文检索的方法 客户端全文检索(适用于小型数据集) 使用 flexsearch 或 lunr.js 等轻量级库实现前端全文检索: import FlexSearch from 'fle…

vue循环数组实现

vue循环数组实现

vue循环数组的实现方法 在Vue中循环数组主要通过v-for指令实现,以下是几种常见用法: 基本数组循环 使用v-for指令遍历数组,可以通过(item, index)的语法获取当前项和索引值:…

vue实现多个tab

vue实现多个tab

Vue 实现多个 Tab 的方法 使用动态组件切换 在 Vue 中可以通过动态组件 <component :is="currentTab"> 结合 v-for 和 v-bind 实现多个…

vue实现菜单调用

vue实现菜单调用

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

vue 移动端实现签名

vue 移动端实现签名

Vue 移动端签名实现方法 在移动端实现签名功能,可以通过HTML5的Canvas结合触摸事件完成。以下是具体实现步骤: 使用Canvas绘制签名 安装vue-signature-pad插件或直…

vue实现安全免登录

vue实现安全免登录

Vue 实现安全免登录的方案 免登录功能通常通过持久化认证状态(如 Token)实现,但需兼顾安全性。以下是基于 Vue 的常见实现方案: 基于 Token 的免登录 登录成功后存储 Toke…