当前位置:首页 > 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
分享给朋友:

相关文章

antd vue 实现

antd vue 实现

使用 Ant Design Vue 实现功能 Ant Design Vue 是基于 Vue.js 的 UI 组件库,提供了丰富的组件和设计规范。以下是一些常见功能的实现方法。 安装 Ant Des…

vue实现登出

vue实现登出

实现Vue登出功能 登出功能通常涉及清除用户会话、令牌或本地存储的数据,并重定向到登录页面。以下是几种常见的实现方式: 清除用户令牌和状态 在Vuex的store中定义一个logout mutati…

vue实现曲线

vue实现曲线

Vue 实现曲线的方法 在 Vue 中实现曲线可以通过多种方式,包括使用 SVG、Canvas 或第三方库如 D3.js、ECharts 等。以下是几种常见的方法: 使用 SVG 绘制曲线 SVG…

vue实现groupbox

vue实现groupbox

Vue 实现 GroupBox 组件 在 Vue 中实现类似 GroupBox 的效果可以通过自定义组件完成。GroupBox 通常是一个带有标题的边框容器,用于将相关控件分组显示。 基本实现方法…

vue实现menu

vue实现menu

Vue 实现 Menu 的方法 使用 Element UI 的 Menu 组件 Element UI 提供了现成的 Menu 组件,适合快速实现导航菜单。安装 Element UI 后,可以直接使用…

vue实现hovuer

vue实现hovuer

Vue 实现 Hover 效果 在 Vue 中实现 hover 效果可以通过多种方式完成,以下是几种常见的方法: 使用 CSS 直接控制 通过 :hover 伪类实现,无需额外的 JavaScri…