当前位置:首页 > VUE

实现简易vue

2026-01-12 18:51:37VUE

实现简易 Vue 的核心思路

实现一个简易 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; // 标记当前 Watcher
    this.oldValue = vm[key]; // 触发 getter 收集依赖
    Dep.target = null;
  }
  update() {
    const newValue = this.vm[this.key];
    if (newValue !== this.oldValue) {
      this.cb(newValue);
    }
  }
}

模板编译

通过编译模板解析指令(如 v-model)和插值表达式(如 {{}}),并绑定更新函数。

class Compiler {
  constructor(el, vm) {
    this.$vm = vm;
    this.$el = document.querySelector(el);
    this.compile(this.$el);
  }
  compile(node) {
    node.childNodes.forEach(child => {
      if (child.nodeType === 1) { // 元素节点
        this.compileElement(child);
      } else if (child.nodeType === 3 && /\{\{(.*)\}\}/.test(child.textContent)) { // 文本节点
        this.compileText(child, RegExp.$1);
      }
      if (child.childNodes.length) {
        this.compile(child);
      }
    });
  }
  compileElement(node) {
    Array.from(node.attributes).forEach(attr => {
      if (attr.name.startsWith('v-')) {
        const dir = attr.name.substring(2);
        this[dir] && this[dir](node, attr.value);
      }
    });
  }
  compileText(node, key) {
    this.update(node, key, 'text');
  }
  text(node, key) {
    this.update(node, key, 'text');
  }
  model(node, key) {
    this.update(node, key, 'model');
    node.addEventListener('input', e => {
      this.$vm[key] = e.target.value;
    });
  }
  update(node, key, type) {
    const updater = {
      text: () => node.textContent = this.$vm[key],
      model: () => node.value = this.$vm[key]
    };
    updater[type]();
    new Watcher(this.$vm, key, () => updater[type]());
  }
}

整合为 Vue 类

将上述模块整合为一个简易 Vue 类。

实现简易vue

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

使用示例

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

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

关键点说明

  • 数据劫持:通过 Object.defineProperty 监听属性变化。
  • 依赖收集:在 getter 中收集依赖,在 setter 中触发更新。
  • 模板编译:解析 DOM 节点,绑定指令和插值表达式。
  • 观察者模式Watcher 作为中介,连接数据变更与视图更新。

标签: 简易vue
分享给朋友:

相关文章

vue实现视窗

vue实现视窗

Vue 实现视窗功能 在 Vue 中实现视窗功能通常涉及监听浏览器窗口大小变化、响应式布局或创建自定义弹窗组件。以下是几种常见实现方式: 监听浏览器窗口大小变化 使用 Vue 的 mounted 和…

vue实现iframe

vue实现iframe

Vue 中实现 iframe 的方法 在 Vue 项目中,可以通过多种方式实现 iframe 的嵌入。以下是几种常见的方法: 使用原生 HTML iframe 标签 直接在 Vue 组件的模板中使用…

vue 路由 实现

vue 路由 实现

Vue 路由实现方法 Vue Router 是 Vue.js 的官方路由管理器,用于构建单页面应用(SPA)。以下是实现 Vue 路由的详细步骤: 安装 Vue Router 通过 npm 或 ya…

vue实现socket

vue实现socket

Vue 中实现 WebSocket 通信 在 Vue 项目中实现 WebSocket 通信可以通过原生 WebSocket API 或第三方库(如 socket.io-client)完成。以下是两种常…

vue实现handsontable

vue实现handsontable

Vue 中实现 Handsontable 要在 Vue 项目中集成 Handsontable,可以使用官方提供的 @handsontable/vue 封装库。以下是一个完整的实现步骤。 安装依赖 确…

vue能实现

vue能实现

Vue.js 是一个流行的前端框架,能够实现多种功能。以下是 Vue 能够实现的主要功能和特性: 响应式数据绑定 Vue 的核心特性之一是响应式数据绑定。通过数据驱动视图,当数据发生变化时,视图会自…