当前位置:首页 > VUE

简易实现vue

2026-02-25 15:32:58VUE

简易 Vue 实现

以下是一个简化版 Vue 的实现思路,涵盖核心功能:数据响应式、模板编译和虚拟 DOM。

数据响应式

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

class Dep {
  constructor() {
    this.subs = [];
  }

  addSub(sub) {
    this.subs.push(sub);
  }

  notify() {
    this.subs.forEach(sub => sub.update());
  }
}

模板编译

将模板字符串解析为 AST,并生成渲染函数。

简易实现vue

class Compiler {
  constructor(el, vm) {
    this.$vm = vm;
    this.$el = document.querySelector(el);
    this.compile(this.$el);
  }

  compile(node) {
    const childNodes = node.childNodes;
    Array.from(childNodes).forEach(child => {
      if (this.isElement(child)) {
        this.compileElement(child);
      } else if (this.isInterpolation(child)) {
        this.compileText(child);
      }
      if (child.childNodes && child.childNodes.length > 0) {
        this.compile(child);
      }
    });
  }

  isElement(node) {
    return node.nodeType === 1;
  }

  isInterpolation(node) {
    return node.nodeType === 3 && /\{\{(.*)\}\}/.test(node.textContent);
  }

  compileText(node) {
    const exp = RegExp.$1.trim();
    this.update(node, exp, 'text');
  }

  compileElement(node) {
    const attrs = node.attributes;
    Array.from(attrs).forEach(attr => {
      const attrName = attr.name;
      const exp = attr.value;
      if (this.isDirective(attrName)) {
        const dir = attrName.substring(2);
        this[dir] && this[dir](node, exp);
      }
    });
  }

  isDirective(attr) {
    return attr.startsWith('v-');
  }

  text(node, exp) {
    this.update(node, exp, 'text');
  }

  update(node, exp, dir) {
    const updater = dir + 'Updater';
    updater && this[updater](node, this.$vm[exp]);
    new Watcher(this.$vm, exp, value => {
      this[updater](node, value);
    });
  }

  textUpdater(node, value) {
    node.textContent = value;
  }
}

虚拟 DOM 和 Watcher

通过 Watcher 连接响应式数据和视图更新。

class Watcher {
  constructor(vm, key, cb) {
    this.$vm = vm;
    this.key = key;
    this.cb = cb;
    Dep.target = this;
    this.$vm[this.key];
    Dep.target = null;
  }

  update() {
    this.cb.call(this.$vm, this.$vm[this.key]);
  }
}

主类

整合以上功能实现简易 Vue 类。

class Vue {
  constructor(options) {
    this.$options = options;
    this.$data = options.data;
    new Observer(this.$data);
    Object.keys(this.$data).forEach(key => {
      this.proxyData(key);
    });
    new Compiler(options.el, this);
  }

  proxyData(key) {
    Object.defineProperty(this, key, {
      get() {
        return this.$data[key];
      },
      set(newVal) {
        this.$data[key] = newVal;
      }
    });
  }
}

使用示例

<div id="app">
  <p>{{ message }}</p>
  <button v-text="btnText"></button>
</div>

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

  setTimeout(() => {
    app.message = 'Hello World';
  }, 1000);
</script>

核心原理

  • 响应式系统:通过数据劫持监听属性变化。
  • 依赖收集:在 getter 中收集依赖,在 setter 中触发更新。
  • 模板编译:解析模板指令和插值表达式。
  • 虚拟 DOM:通过 Watcher 实现数据和视图的绑定。

以上代码实现了一个简易版的 Vue,涵盖了 Vue 的核心功能。实际 Vue 的实现更为复杂,包括组件系统、生命周期、指令系统等。

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

相关文章

实现vue组件

实现vue组件

Vue 组件的基本实现 Vue 组件是 Vue.js 的核心特性之一,允许将 UI 拆分为独立、可复用的模块。以下是实现 Vue 组件的几种方式: 单文件组件 (SFC) 使用 .vue 文件格式,…

vue实现同步

vue实现同步

Vue 实现同步的方法 在 Vue 中实现同步操作通常涉及数据绑定、状态管理和异步操作的处理。以下是几种常见的方法: 使用计算属性(Computed Properties) 计算属性基于响应式依赖…

vue实现引导

vue实现引导

Vue 实现引导功能的方法 使用第三方库 推荐使用 driver.js 或 intro.js 这类专门为 Vue 设计的引导库。这些库提供了完整的 API 和样式,能够快速实现引导功能。 安装 d…

vue实现$.extend

vue实现$.extend

Vue 实现类似 jQuery 的 $.extend 功能 在 Vue 中实现类似 jQuery 的 $.extend 功能,可以通过多种方式完成。$.extend 主要用于合并多个对象的属性,Vue…

vue实现拍照

vue实现拍照

Vue实现拍照功能 在Vue中实现拍照功能通常需要结合浏览器的MediaDevices API和Canvas元素。以下是具体实现方法: 安装依赖(可选) 如果需要更简单的封装,可以安装vue-w…

vue实现token

vue实现token

Vue 中实现 Token 认证的方法 在 Vue 中实现 Token 认证通常涉及前端与后端的交互,包括 Token 的获取、存储、发送和刷新等操作。以下是具体实现步骤: 获取 Token 用户…