当前位置:首页 > VUE

自己实现vue

2026-01-08 03:16:56VUE

实现简易版 Vue.js 核心功能

要实现一个简易版 Vue.js,需要理解其核心功能:数据响应式、模板编译、依赖收集和虚拟 DOM。以下分模块实现关键功能。

数据响应式(Reactivity)

通过 Object.definePropertyProxy 实现数据劫持。当数据变化时,自动触发更新。

自己实现vue

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) {
    this.walk(val); // 递归处理嵌套对象
    const dep = new Dep();
    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(); // 通知更新
      }
    });
  }
}

依赖收集(Dependency Tracking)

通过发布-订阅模式管理依赖关系,每个响应式属性对应一个 Dep 实例。

class Dep {
  constructor() {
    this.subs = [];
  }
  addSub(sub) {
    this.subs.push(sub);
  }
  notify() {
    this.subs.forEach(sub => sub.update());
  }
}
Dep.target = null; // 静态属性指向当前 Watcher

观察者(Watcher)

Watcher 作为中介,在数据变化时触发回调(如更新视图)。

自己实现vue

class Watcher {
  constructor(vm, key, cb) {
    this.vm = vm;
    this.key = key;
    this.cb = cb;
    Dep.target = this;
    this.oldValue = vm[key]; // 触发 getter 收集依赖
    Dep.target = null;
  }
  update() {
    const newValue = this.vm[this.key];
    if (newValue === this.oldValue) return;
    this.cb(newValue);
    this.oldValue = newValue;
  }
}

模板编译(Compilation)

解析模板中的指令(如 v-model)和插值表达式({{}}),绑定数据和事件。

class Compiler {
  constructor(el, vm) {
    this.$vm = vm;
    this.$el = document.querySelector(el);
    this.compile(this.$el);
  }
  compile(node) {
    node.childNodes.forEach(node => {
      if (node.nodeType === 1) this.compileElement(node);
      else if (this.isInterpolation(node)) this.compileText(node);
      if (node.childNodes.length > 0) this.compile(node);
    });
  }
  isInterpolation(node) {
    return node.nodeType === 3 && /\{\{(.*)\}\}/.test(node.textContent);
  }
  compileText(node) {
    const exp = RegExp.$1.trim();
    this.update(node, exp, 'text');
  }
  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);
      }
    });
  }
  text(node, exp) {
    this.update(node, exp, 'text');
  }
  model(node, exp) {
    this.update(node, exp, 'model');
    node.addEventListener('input', e => {
      this.$vm[exp] = e.target.value;
    });
  }
  update(node, exp, dir) {
    const updater = dir + 'Updater';
    this[updater] && this[updater](node, this.$vm[exp]);
    new Watcher(this.$vm, exp, value => {
      this[updater](node, value);
    });
  }
  textUpdater(node, value) {
    node.textContent = value;
  }
  modelUpdater(node, value) {
    node.value = value;
  }
}

整合为 Vue 类

将上述模块组合成完整的 Vue 类。

class Vue {
  constructor(options) {
    this.$options = options;
    this.$data = options.data();
    this.observe(this.$data);
    this.proxyData(this.$data);
    new Compiler(options.el, this);
  }
  observe(data) {
    new Observer(data);
  }
  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 Mini Vue!' };
    }
  });
</script>

关键点总结

  • 数据响应式:通过劫持数据属性的访问和修改,实现自动更新。
  • 依赖收集:在 getter 中收集依赖,在 setter 中触发更新。
  • 模板编译:解析指令和插值,建立数据与 DOM 的绑定关系。
  • 观察者模式Watcher 作为桥梁连接数据变更与视图更新。

以上实现省略了虚拟 DOM、组件系统等高级功能,但涵盖了 Vue 最核心的响应式原理。

标签: vue
分享给朋友:

相关文章

vue实现点击样式

vue实现点击样式

Vue 实现点击样式的方法 在 Vue 中实现点击样式可以通过多种方式完成,以下是几种常见的方法: 方法一:使用 v-bind:class 动态绑定类名 通过数据驱动的方式动态切换类名,结合…

vue实现组件循环

vue实现组件循环

Vue 组件循环的实现方法 在 Vue 中实现组件循环通常使用 v-for 指令,可以循环渲染数组或对象的数据到组件上。 基本数组循环 通过 v-for 指令遍历数组,渲染多个相同结构的组件。…

vue实现路由导航

vue实现路由导航

路由导航的实现方式 在Vue中,路由导航主要通过Vue Router实现。Vue Router是Vue.js官方的路由管理器,用于构建单页面应用(SPA)。 基本路由配置 安装Vue Router后…

vue伪函数实现

vue伪函数实现

Vue 伪函数实现方法 伪函数(Mock Function)在 Vue 中常用于测试或模拟某些逻辑,以下是几种常见的实现方式: 使用 Jest 的 jest.fn() 在单元测试中,可以通过 Jes…

vue表格实现教学

vue表格实现教学

Vue 表格实现方法 使用原生HTML表格 在Vue模板中直接使用HTML的<table>标签,结合v-for动态渲染数据: <template> <table&g…

vue表单实现搜索

vue表单实现搜索

实现Vue表单搜索功能 在Vue中实现表单搜索功能通常涉及表单绑定、事件处理和搜索逻辑。以下是具体实现方法: 数据绑定与表单结构 使用v-model实现表单与Vue数据的双向绑定: <tem…