当前位置:首页 > 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实现项目的关键方法 搭建基础环境 安装Node.js和npm/yarn,确保开发环境具备运行Vue的能力。通过Vue CLI快速初始化项目结构,选择所需配置(如Babel、Router、Vu…

vue卖座网实现

vue卖座网实现

Vue 卖座网实现 项目结构搭建 使用 Vue CLI 快速初始化项目,安装必要依赖如 Vue Router、Vuex、Axios。 创建核心目录结构:components(通用组件)、views(页…

vue实现字母添加排序

vue实现字母添加排序

实现字母添加排序的方法 在Vue中实现字母添加排序功能,可以通过以下步骤完成: 创建Vue实例并定义数据 new Vue({ el: '#app', data: { letters…

vue原型实现

vue原型实现

Vue 原型实现的关键点 Vue.js 的原型系统是其响应式机制的核心部分,通过原型链实现数据的动态绑定和依赖收集。以下是实现 Vue 原型的主要技术要点。 数据响应式原理 Vue 通过 Objec…

eventbus vue实现

eventbus vue实现

EventBus 实现原理 EventBus 是一种发布/订阅模式,用于 Vue 组件间的通信。核心是通过一个中央事件总线管理事件监听和触发。 创建 EventBus 在 Vue 项目中创建一个独立…

vue实现切换

vue实现切换

Vue 实现切换功能的方法 在 Vue 中实现切换功能可以通过多种方式实现,以下是一些常见的方法: 使用 v-if 和 v-else 指令 通过条件渲染实现切换功能,适用于简单的显示/隐藏场景。…