当前位置:首页 > VUE

实现简易vue

2026-01-12 18:51:37VUE

实现简易 Vue 的核心思路

实现一个简易 Vue 需要模拟其核心功能:数据响应式、模板编译和依赖收集。以下分模块介绍实现方法。

数据响应式

通过 Object.definePropertyProxy 实现数据劫持,监听数据变化并触发更新。

实现简易vue

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(); // 触发更新
      }
    });
  }
}

依赖收集与发布

通过 Dep(依赖管理器)和 Watcher(观察者)实现依赖的收集与通知。

实现简易vue

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; // 标记当前 Watcher
    this.oldValue = vm[key]; // 触发 getter 收集依赖
    Dep.target = null;
  }
  update() {
    const newValue = this.vm[this.key];
    if (newValue !== this.oldValue) {
      this.cb(newValue);
    }
  }
}

模板编译

通过编译模板解析指令(如 v-model)和插值表达式(如 {{}}),并绑定更新函数。

class Compiler {
  constructor(el, vm) {
    this.$vm = vm;
    this.$el = document.querySelector(el);
    this.compile(this.$el);
  }
  compile(node) {
    node.childNodes.forEach(child => {
      if (child.nodeType === 1) { // 元素节点
        this.compileElement(child);
      } else if (child.nodeType === 3 && /\{\{(.*)\}\}/.test(child.textContent)) { // 文本节点
        this.compileText(child, RegExp.$1);
      }
      if (child.childNodes.length) {
        this.compile(child);
      }
    });
  }
  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);
      }
    });
  }
  compileText(node, key) {
    this.update(node, key, 'text');
  }
  text(node, key) {
    this.update(node, key, 'text');
  }
  model(node, key) {
    this.update(node, key, 'model');
    node.addEventListener('input', e => {
      this.$vm[key] = e.target.value;
    });
  }
  update(node, key, type) {
    const updater = {
      text: () => node.textContent = this.$vm[key],
      model: () => node.value = this.$vm[key]
    };
    updater[type]();
    new Watcher(this.$vm, key, () => updater[type]());
  }
}

整合为 Vue 类

将上述模块整合为一个简易 Vue 类。

class Vue {
  constructor(options) {
    this.$options = options;
    this.$data = options.data();
    new Observer(this.$data);
    this.proxyData(this.$data);
    new Compiler(options.el, this);
  }
  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 Vue!' };
    }
  });
</script>

关键点说明

  • 数据劫持:通过 Object.defineProperty 监听属性变化。
  • 依赖收集:在 getter 中收集依赖,在 setter 中触发更新。
  • 模板编译:解析 DOM 节点,绑定指令和插值表达式。
  • 观察者模式Watcher 作为中介,连接数据变更与视图更新。

标签: 简易vue
分享给朋友:

相关文章

vue实现anchor

vue实现anchor

Vue 实现 Anchor(锚点)功能 在 Vue 中实现锚点功能可以通过多种方式完成,以下是几种常见的方法: 使用 HTML 原生锚点 HTML 原生锚点是最简单的方式,通过 <a>…

vue 实现目录

vue 实现目录

Vue 实现目录的方法 在 Vue 项目中实现目录功能,可以通过以下几种方式实现,具体取决于需求和技术栈。 使用 Vue Router 实现路由目录 Vue Router 是 Vue.js 的官方路…

vue实现aop切面

vue实现aop切面

Vue 实现 AOP 切面编程的方法 在 Vue 中实现 AOP(面向切面编程)可以通过多种方式,以下是几种常见的实现方法: 使用 Vue 混入(Mixins) Vue 的混入机制可以用于实现横切关…

vue实现sql操作

vue实现sql操作

在Vue中实现SQL操作通常需要结合后端服务或本地数据库技术,因为前端JavaScript无法直接连接SQL数据库。以下是几种常见的实现方式: 通过API与后端交互 Vue前端通过HTTP请求(如a…

vue实现添加用户

vue实现添加用户

Vue 实现添加用户功能 数据绑定与表单设计 在 Vue 中实现添加用户功能,首先需要设计一个表单,用于收集用户输入的数据。通过 v-model 实现双向数据绑定,确保表单数据与 Vue 实例中的数据…

vue实现tab换行

vue实现tab换行

Vue实现Tab切换的常见方法 使用Vue实现Tab切换功能可以通过多种方式完成,以下是几种常见的方法: 动态组件结合v-if或v-show 通过v-if或v-show控制不同Tab内容的显示…