当前位置:首页 > VUE

自实现vue

2026-01-08 00:32:18VUE

实现 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();
      }
    });
  }
}

依赖收集与派发更新

通过依赖收集器(Dep)和观察者(Watcher)实现数据变化时的视图更新。

自实现vue

class Dep {
  constructor() {
    this.subs = [];
  }

  addSub(sub) {
    this.subs.push(sub);
  }

  notify() {
    this.subs.forEach(sub => sub.update());
  }
}

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

模板编译

将模板字符串解析为 AST(抽象语法树),然后生成渲染函数。

class Compiler {
  constructor(el, vm) {
    this.el = document.querySelector(el);
    this.vm = vm;
    this.compile(this.el);
  }

  compile(node) {
    const childNodes = node.childNodes;
    Array.from(childNodes).forEach(childNode => {
      if (this.isElementNode(childNode)) {
        this.compileElement(childNode);
      } else if (this.isTextNode(childNode)) {
        this.compileText(childNode);
      }
      if (childNode.childNodes && childNode.childNodes.length) {
        this.compile(childNode);
      }
    });
  }

  isElementNode(node) {
    return node.nodeType === 1;
  }

  isTextNode(node) {
    return node.nodeType === 3;
  }

  compileElement(node) {
    const attributes = node.attributes;
    Array.from(attributes).forEach(attr => {
      const attrName = attr.name;
      if (this.isDirective(attrName)) {
        const dir = attrName.substring(2);
        const expr = attr.value;
        this[dir] && this[dir](node, expr);
      }
    });
  }

  compileText(node) {
    const reg = /\{\{(.+?)\}\}/;
    const value = node.textContent;
    if (reg.test(value)) {
      const key = RegExp.$1.trim();
      node.textContent = value.replace(reg, this.vm[key]);
      new Watcher(this.vm, key, newVal => {
        node.textContent = newVal;
      });
    }
  }

  isDirective(attrName) {
    return attrName.startsWith('v-');
  }

  model(node, expr) {
    node.value = this.vm[expr];
    new Watcher(this.vm, expr, newVal => {
      node.value = newVal;
    });
    node.addEventListener('input', e => {
      this.vm[expr] = e.target.value;
    });
  }
}

虚拟 DOM 实现

虚拟 DOM 是对真实 DOM 的抽象表示,通过 Diff 算法高效更新视图。

自实现vue

class VNode {
  constructor(tag, data, children, text, elm) {
    this.tag = tag;
    this.data = data;
    this.children = children;
    this.text = text;
    this.elm = elm;
  }
}

function createElement(tag, data, children) {
  return new VNode(tag, data, children, undefined, undefined);
}

function createTextNode(text) {
  return new VNode(undefined, undefined, undefined, text, undefined);
}

组件系统

组件是 Vue 的核心概念之一,通过递归方式实现组件树。

class Component {
  constructor(options) {
    this.data = options.data;
    this.methods = options.methods;
    this.template = options.template;
    this.el = options.el;
    this.init();
  }

  init() {
    const observer = new Observer(this.data);
    new Compiler(this.el, this);
  }
}

整合实现

将以上功能整合为一个简易的 Vue 类。

class Vue {
  constructor(options) {
    this.$options = options;
    this._data = options.data;
    this.observer = 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;
        }
      });
    });
  }
}

使用示例

以下是如何使用自实现的 Vue:

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

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

总结

通过实现数据响应式、依赖收集、模板编译和虚拟 DOM,可以构建一个简化版的 Vue。虽然功能不如官方 Vue 完善,但核心原理相同。进一步扩展可以添加计算属性、生命周期钩子等功能。

标签: vue
分享给朋友:

相关文章

vue实现图片分析

vue实现图片分析

Vue 实现图片分析的方法 在 Vue 中实现图片分析通常涉及图片上传、预览、后端交互以及分析结果展示等功能。以下是几种常见的实现方式: 使用 HTML5 File API 和 Canvas 进行…

vue页面分离的实现

vue页面分离的实现

Vue页面分离的实现方法 将Vue页面分离为多个组件或模块,有助于提升代码可维护性和复用性。以下是几种常见的实现方式: 组件化拆分 通过将页面拆分为多个子组件,每个组件负责特定功能或UI部分。使用i…

vue实现录音文件播放

vue实现录音文件播放

使用 Vue 实现录音文件播放 准备工作 确保项目中已安装必要的依赖,如 vue-audio-recorder 或原生 Web Audio API。录音文件播放通常涉及录音、存储和播放三个核心环节。…

vue实现签约合作弹窗

vue实现签约合作弹窗

实现签约合作弹窗的步骤 使用Vue实现签约合作弹窗可以通过组件化方式完成,结合模态框和表单交互逻辑。以下是具体实现方法: 1. 创建弹窗组件 新建一个Vue组件文件(如SignContractDi…

vue实现绑卡的原理

vue实现绑卡的原理

Vue 实现绑卡的原理 Vue 实现绑卡功能通常涉及前端表单处理、数据绑定、验证以及和后端 API 的交互。以下是实现绑卡功能的核心原理和步骤: 数据绑定与表单处理 Vue 通过 v-model 指…

vue实现打印二维码

vue实现打印二维码

安装二维码生成库 使用 qrcode 或 vue-qrcode 库生成二维码。通过 npm 安装: npm install qrcode vue-qrcode 生成二维码 在 Vue 组…