当前位置:首页 > 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 中实现静态查询通常指不依赖后端接口,直接在前端处理数据筛选或搜索功能。以下是几种常见实现方式: 使用计算属性过滤数据 通过计算属性对静态数据进行筛选,适合简单查询场…

vue实现浮标

vue实现浮标

Vue 实现浮动按钮(浮标) 使用 Vue 实现浮动按钮可以通过多种方式完成,以下是几种常见的方法: 使用 CSS 定位和 Vue 组件 创建 Vue 组件并配合 CSS 固定定位实现浮动按钮:…

vue实现ide

vue实现ide

Vue 实现 IDE 的基本思路 使用 Vue 构建一个简易的集成开发环境(IDE)需要整合代码编辑器、文件管理、终端模拟等功能。以下是关键实现步骤和推荐工具。 核心功能模块 代码编辑器 使用…

vue实现翻页

vue实现翻页

Vue实现翻页功能 在Vue中实现翻页功能通常需要结合分页组件和数据请求逻辑。以下是常见的实现方法: 使用Element UI分页组件 安装Element UI后,可以直接使用其分页组件: <…

vue实现复制

vue实现复制

Vue 实现复制功能 在 Vue 中实现复制功能可以通过多种方式完成,以下是几种常见的方法: 方法一:使用 Clipboard API Clipboard API 是现代浏览器提供的一种原生 AP…

vue实现循环

vue实现循环

Vue 实现循环的方法 在 Vue 中,可以通过 v-for 指令实现循环渲染列表或对象。以下是几种常见的用法: 遍历数组 使用 v-for 遍历数组时,可以同时获取当前项和索引: <ul&…