当前位置:首页 > 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的<video>元素或第三方播放器库。以下是几种常见实现方式: 使用原生HTML5 video元素 通过ref获取v…

vue实现缩放

vue实现缩放

Vue 实现缩放的方法 在 Vue 中实现缩放功能可以通过多种方式完成,以下是一些常见的方法: 使用 CSS transform 属性 通过 CSS 的 transform: scale() 属性可…

vue tab实现

vue tab实现

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

vue 实现拖拉

vue 实现拖拉

Vue 实现拖拽功能的方法 使用 HTML5 原生拖放 API HTML5 提供了原生的拖放 API,可以通过 draggable 属性、dragstart、dragend、dragover 和 dr…

vue实现按钮

vue实现按钮

Vue 实现按钮的方法 使用原生 HTML 按钮 在 Vue 模板中可以直接使用 HTML 的 <button> 元素,通过 v-on 或 @ 绑定点击事件。 <template&…

vue实现分站

vue实现分站

Vue 实现分站的方案 在 Vue 中实现分站功能通常涉及路由配置、环境变量管理和动态加载资源。以下是几种常见的实现方式: 基于路由的分站实现 通过 Vue Router 配置多路由,区分不同站点的…