当前位置:首页 > VUE

原生实现vue功能

2026-01-14 02:48:48VUE

原生 JavaScript 实现 Vue 核心功能

使用原生 JavaScript 模拟 Vue 的核心功能(如数据绑定、虚拟 DOM、响应式更新等),可以通过以下方式实现:

数据响应式系统

通过 Object.definePropertyProxy 监听数据变化,触发更新:

原生实现vue功能

function observe(data) {
  if (!data || typeof data !== 'object') return;
  Object.keys(data).forEach(key => {
    let value = data[key];
    const dep = new Dep(); // 依赖收集器
    observe(value); // 递归监听
    Object.defineProperty(data, key, {
      get() {
        Dep.target && dep.addSub(Dep.target); // 收集依赖
        return value;
      },
      set(newVal) {
        if (newVal === value) return;
        value = newVal;
        observe(newVal); // 新值也需要监听
        dep.notify(); // 触发更新
      }
    });
  });
}

class Dep {
  constructor() {
    this.subs = [];
  }
  addSub(sub) {
    this.subs.push(sub);
  }
  notify() {
    this.subs.forEach(sub => sub.update());
  }
}

模板编译与虚拟 DOM

实现简单的模板解析和虚拟 DOM 生成:

原生实现vue功能

function compile(template, data) {
  const el = document.querySelector(template);
  const fragment = document.createDocumentFragment();
  let child;
  while (child = el.firstChild) {
    fragment.appendChild(child);
  }
  replace(fragment, data);
  el.appendChild(fragment);
}

function replace(node, data) {
  const reg = /\{\{(.*?)\}\}/g;
  if (node.nodeType === 3) { // 文本节点
    const text = node.textContent;
    if (reg.test(text)) {
      const key = RegExp.$1.trim();
      node.textContent = text.replace(reg, data[key]);
      new Watcher(data, key, (val) => {
        node.textContent = text.replace(reg, val);
      });
    }
    return;
  }
  if (node.nodeType === 1) { // 元素节点
    const attrs = node.attributes;
    for (let i = 0; i < attrs.length; i++) {
      const name = attrs[i].name;
      if (name.startsWith('v-')) {
        const exp = attrs[i].value;
        node.value = data[exp];
        new Watcher(data, exp, (val) => {
          node.value = val;
        });
        node.addEventListener('input', (e) => {
          data[exp] = e.target.value;
        });
      }
    }
  }
  Array.from(node.childNodes).forEach(child => replace(child, data));
}

观察者与依赖管理

实现 Watcher 类连接响应式数据和视图:

class Watcher {
  constructor(data, key, cb) {
    this.data = data;
    this.key = key;
    this.cb = cb;
    Dep.target = this;
    this.value = data[key]; // 触发getter收集依赖
    Dep.target = null;
  }
  update() {
    const newVal = this.data[this.key];
    if (newVal !== this.value) {
      this.value = newVal;
      this.cb(newVal);
    }
  }
}

简易调用示例

整合以上功能实现类似 Vue 的调用方式:

class MiniVue {
  constructor(options) {
    this.$options = options;
    this.$data = options.data();
    observe(this.$data);
    compile(options.el, this.$data);
  }
}

// 使用示例
new MiniVue({
  el: '#app',
  data() {
    return { message: 'Hello MiniVue', count: 0 };
  }
});

注意事项

  1. 此实现仅为演示核心原理,实际 Vue 源码包含更多优化(如异步更新、Diff 算法等)。
  2. ProxyObject.defineProperty 能更好地处理数组和嵌套对象。
  3. 现代前端框架通常使用虚拟 DOM 和差异化更新算法提升性能。
  4. 完整实现还需考虑组件系统、生命周期等复杂功能。

标签: 功能vue
分享给朋友:

相关文章

vue前端实现打印功能

vue前端实现打印功能

使用Vue实现前端打印功能 在Vue项目中实现打印功能可以通过多种方式完成,以下是几种常见的方法: 使用window.print()方法 这是最简单的打印方式,直接调用浏览器的打印功能。 me…

vue实现方法

vue实现方法

Vue 实现方法 Vue 是一种流行的前端框架,用于构建用户界面和单页应用。以下是几种常见的 Vue 实现方法: 创建 Vue 实例 通过 new Vue() 创建一个 Vue 实例,传入配置对象,…

vue评分实现

vue评分实现

Vue 评分组件实现方法 使用第三方库(如 Element UI) 安装 Element UI: npm install element-ui 引入并注册组件: import Vue from…

vue分类实现

vue分类实现

Vue分类实现方法 在Vue中实现分类功能通常涉及数据分组、动态渲染和交互逻辑。以下是几种常见的实现方式: 基于计算属性的分类 通过计算属性对原始数据进行分组处理,适合静态或少量数据分类: com…

vue的实现

vue的实现

Vue 的实现原理 Vue 是一个渐进式 JavaScript 框架,其核心实现主要包括响应式系统、虚拟 DOM、模板编译和组件化机制。以下是 Vue 实现的主要技术细节。 响应式系统 Vue 的响…

vue 实现列表

vue 实现列表

Vue 实现列表的方法 在 Vue 中实现列表通常使用 v-for 指令,结合数组或对象数据渲染动态列表。以下是几种常见的实现方式: 基础列表渲染 使用 v-for 指令遍历数组,渲染列表项。ite…