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

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实现多个tab

vue实现多个tab

Vue 实现多个 Tab 的方法 使用动态组件切换 在 Vue 中可以通过动态组件 <component :is="currentTab"> 结合 v-for 和 v-bind 实现多个…

vue登录逻辑的实现

vue登录逻辑的实现

Vue 登录逻辑实现 前端实现 创建登录组件 在 Vue 项目中创建一个登录组件,通常命名为 Login.vue。该组件包含表单元素,如用户名和密码输入框,以及提交按钮。 <template&…

vue如何实现放大缩小

vue如何实现放大缩小

Vue实现放大缩小功能的方法 在Vue中实现元素的放大缩小功能,可以通过CSS变换、第三方库或直接操作DOM样式来实现。以下是几种常见的方法: 使用CSS transform属性 通过绑定Vue的…

vue实现下载暂停

vue实现下载暂停

Vue实现下载暂停功能 在Vue中实现下载暂停功能,通常需要结合XMLHttpRequest或Fetch API的AbortController来控制请求中断。以下是具体实现方法: 使用XMLHtt…

vue实现绑卡的原理

vue实现绑卡的原理

Vue 实现绑卡的原理 Vue 实现绑卡功能通常涉及前端表单处理、数据绑定、验证以及和后端 API 的交互。以下是实现绑卡功能的核心原理和步骤: 数据绑定与表单处理 Vue 通过 v-model…

vue实现用户信息删除

vue实现用户信息删除

Vue 实现用户信息删除功能 在 Vue 中实现用户信息删除功能通常涉及前端界面交互和后端 API 调用。以下是实现步骤: 前端界面设计 创建删除按钮或操作项,通常使用 @click 事件触发删除操…