当前位置:首页 > VUE

自己实现vue

2026-03-07 16:12:51VUE

实现简易版 Vue 的核心思路

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();
      }
    });
  }
}

依赖收集(发布-订阅模式)

通过 DepWatcher 实现依赖收集和通知更新。

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;
    this.oldValue = vm[key];
    Dep.target = null;
  }
  update() {
    const newValue = this.vm[this.key];
    if (newValue === this.oldValue) return;
    this.cb(newValue);
    this.oldValue = newValue;
  }
}

模板编译

解析模板中的指令(如 v-model)和插值表达式(如 {{}}),并建立数据与视图的绑定关系。

class Compiler {
  constructor(el, vm) {
    this.el = document.querySelector(el);
    this.vm = vm;
    this.compile(this.el);
  }
  compile(node) {
    const childNodes = node.childNodes;
    [...childNodes].forEach(child => {
      if (this.isElementNode(child)) {
        this.compileElement(child);
      } else if (this.isTextNode(child)) {
        this.compileText(child);
      }
      if (child.childNodes && child.childNodes.length) {
        this.compile(child);
      }
    });
  }
  isElementNode(node) {
    return node.nodeType === 1;
  }
  isTextNode(node) {
    return node.nodeType === 3;
  }
  compileElement(node) {
    const attributes = node.attributes;
    [...attributes].forEach(attr => {
      const { name, value } = attr;
      if (this.isDirective(name)) {
        const [, directive] = name.split('-');
        const [dirName, eventName] = directive.split(':');
        compileUtil[dirName] && compileUtil[dirName](node, value, this.vm, eventName);
      }
    });
  }
  compileText(node) {
    const content = node.textContent;
    if (/\{\{(.+?)\}\}/.test(content)) {
      compileUtil['text'](node, content, this.vm);
    }
  }
  isDirective(attrName) {
    return attrName.startsWith('v-');
  }
}

实现 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) {
    if (!data || typeof data !== 'object') return;
    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">
  <input v-model="message" />
  <p>{{ message }}</p>
</div>

<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: 'Hello Vue!'
    }
  });
</script>

关键点总结

  • 数据劫持:通过 Object.definePropertyProxy 监听数据变化。
  • 依赖收集:在 getter 中收集依赖,在 setter 中触发更新。
  • 模板编译:解析模板中的指令和插值表达式,建立数据与视图的绑定。
  • Watcher:作为桥梁连接数据劫持和模板编译,触发更新回调。

以上实现了一个简易版的 Vue,包含了核心的响应式系统和模板编译功能。实际 Vue 的实现更为复杂,包括虚拟 DOM、组件系统等更多功能。

标签: vue
分享给朋友:

相关文章

vue懒加载实现难吗

vue懒加载实现难吗

vue懒加载的实现难度 Vue懒加载的实现并不复杂,核心逻辑是通过动态导入(Dynamic Imports)和路由配置或组件异步加载完成。以下是具体实现方法: 路由懒加载实现 在Vue Router…

vue实现pc

vue实现pc

Vue 实现 PC 端应用开发 Vue.js 是一个流行的前端框架,适用于构建 PC 端 Web 应用。以下是关键步骤和最佳实践: 项目初始化 使用 Vue CLI 或 Vite 创建项目:…

vue 实现音乐

vue 实现音乐

Vue 实现音乐播放功能 在 Vue 中实现音乐播放功能,可以通过 HTML5 的 <audio> 元素或第三方库如 howler.js 来实现。以下是两种方法的详细步骤: 使用 HTM…

vue实现标注

vue实现标注

Vue 实现标注功能的方法 使用 Vue 实现标注功能可以通过多种方式实现,以下介绍几种常见的方法: 1. 使用 HTML5 Canvas 实现标注 Canvas 提供了强大的绘图能力,适合实现复…

vue实现listview

vue实现listview

Vue 实现 ListView 的方法 基础列表渲染 使用 v-for 指令可以轻松实现基础列表渲染。在 Vue 中,v-for 用于遍历数组或对象,生成动态列表。 <template>…

vue 实现穿透

vue 实现穿透

Vue 样式穿透的实现方法 在 Vue 中,样式穿透通常指在带有 scoped 属性的样式块中,强制影响子组件的样式。以下是几种常见的实现方式: 使用 >>> 或 /deep/ 选…