当前位置:首页 > 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)实现数据变化时的视图更新。

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 算法高效更新视图。

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:

自实现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中,可以通过结合DOM操作、Canvas绘制及第三方库实现。以下是具体方法: 使用html2canvas库实现 安装…

实现vue模版

实现vue模版

Vue 模板的基本结构 Vue 模板基于 HTML 语法,通过 Vue 的指令和插值实现动态渲染。以下是一个基础模板示例: <template> <div id="…

vue实现select

vue实现select

Vue 实现 Select 组件的方法 在 Vue 中实现 Select 组件可以通过多种方式完成,以下是几种常见的方法: 使用原生 HTML select 元素 原生 HTML 的 <sel…

vue 实现ztree

vue 实现ztree

在Vue中实现类似ZTree的功能,可以通过集成第三方库或自定义组件完成。以下是两种常见方法: 使用vue-tree组件 vue-tree是一个轻量级的Vue树形组件,支持复选框、懒加载等功能,适合…

vue实现tip

vue实现tip

Vue实现Tooltip的方法 使用Vue实现Tooltip可以通过多种方式完成,以下是几种常见的方法: 使用原生HTML的title属性 在Vue模板中直接使用HTML的title属性是最简单的实…

vue弹幕实现

vue弹幕实现

Vue弹幕实现方法 弹幕功能常见于视频直播或评论区,以下是基于Vue的实现方案,涵盖基础弹幕、动画控制及性能优化。 基础弹幕渲染 通过v-for动态渲染弹幕列表,结合CSS实现横向移动效果。弹幕数据…