当前位置:首页 > VUE

自己实现vue

2026-01-08 03:16:56VUE

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

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

数据响应式(Reactivity)

通过 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) {
    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 作为中介,在数据变化时触发回调(如更新视图)。

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 类。

自己实现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实现https

vue实现https

Vue 中实现 HTTPS 的步骤 在 Vue 项目中实现 HTTPS 主要涉及开发环境配置和生产环境部署。以下是具体方法: 开发环境配置(Vue CLI 或 Vite) 使用 mkcert 生成…

vue实现图库

vue实现图库

Vue 实现图库的基本方法 使用 Vue 实现图库功能可以通过多种方式完成,以下是一些常见的方法和实现步骤。 使用 Vue 和第三方库(如 Vue Gallery) 安装 vue-gallery 或…

vue实现心电图

vue实现心电图

Vue 实现心电图效果 在 Vue 中实现心电图效果通常需要结合 Canvas 或 SVG 进行动态绘图,模拟心电图数据的实时变化。以下是两种实现方式的核心思路和代码示例: 使用 Canvas 绘制…

vue 实现原理

vue 实现原理

Vue 实现原理 Vue.js 是一个渐进式 JavaScript 框架,其核心实现原理主要包括响应式系统、虚拟 DOM、模板编译和组件化机制。以下是 Vue 实现原理的核心要点: 响应式系统 Vu…

vue实现投票

vue实现投票

Vue实现投票功能 数据准备 在Vue组件的data中定义投票相关数据,包括选项列表和当前选中状态: data() { return { options: [ { id: 1…

vue实现权限

vue实现权限

Vue 实现权限管理的方法 在 Vue 项目中实现权限管理通常涉及路由控制、按钮权限和接口权限。以下是几种常见的实现方式: 路由权限控制 通过动态路由的方式,根据用户权限加载不同的路由配置。可以使用…