当前位置:首页 > 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:

<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 实现分支的方法 在 Vue 项目中实现分支功能通常涉及条件渲染、动态组件或路由控制。以下是几种常见的实现方式: 条件渲染(v-if/v-show) 使用 Vue 的指令根据条件显示不同内容:…

vue实现文档分享

vue实现文档分享

Vue 实现文档分享功能 文档分享功能通常涉及文件上传、存储、生成分享链接以及权限控制等模块。以下是基于 Vue 的实现方案: 文件上传组件 使用 element-ui 或 ant-design-…

vue实现共享屏幕

vue实现共享屏幕

共享屏幕的基本实现 在Vue中实现共享屏幕功能通常需要结合浏览器的getDisplayMedia API。以下是一个基础实现示例: <template> <div>…

vue前端实现登录

vue前端实现登录

实现登录功能的基本流程 使用Vue实现登录功能需要结合前端框架和后端API交互。以下是一个典型的实现方案: 安装必要依赖 确保项目已安装axios用于HTTP请求: npm install axi…

vue 页签实现

vue 页签实现

Vue 页签实现方法 在 Vue 中实现页签功能通常涉及动态组件、路由或状态管理。以下是几种常见的实现方式: 使用动态组件 通过 Vue 的 <component> 动态组件结合 v-…

vue手动实现弹窗

vue手动实现弹窗

实现弹窗组件的基本结构 在Vue中手动实现弹窗组件,需要创建一个独立的弹窗组件,并通过props控制其显示与隐藏。弹窗组件通常包含遮罩层、内容区域和关闭按钮。 <template>…