当前位置:首页 > VUE

实现简易vue

2026-01-07 18:13:03VUE

实现简易 Vue 的核心思路

Vue 的核心功能包括数据响应式、模板编译和虚拟 DOM。以下是一个简易实现方案,涵盖核心功能模块。

数据响应式系统

通过 Object.definePropertyProxy 实现数据劫持。以下使用 Object.defineProperty 的示例:

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(观察者):

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.vm[this.key]; // 触发 getter 收集依赖
    Dep.target = null;
  }
  update() {
    this.cb.call(this.vm, this.vm[this.key]);
  }
}

模板编译

实现简单的模板解析和指令处理:

class Compiler {
  constructor(el, vm) {
    this.$vm = vm;
    this.$el = document.querySelector(el);
    this.compile(this.$el);
  }
  compile(el) {
    const childNodes = el.childNodes;
    Array.from(childNodes).forEach(node => {
      if (this.isElement(node)) {
        this.compileElement(node);
      } else if (this.isInterpolation(node)) {
        this.compileText(node);
      }
      if (node.childNodes) this.compile(node);
    });
  }
  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 => {
      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');
  }
  update(node, exp, dir) {
    const updater = dir + 'Updater';
    this[updater](node, this.$vm[exp]);
    new Watcher(this.$vm, exp, value => {
      this[updater](node, value);
    });
  }
  textUpdater(node, value) {
    node.textContent = value;
  }
}

整合成 MiniVue 类

将各模块组合成完整框架:

class MiniVue {
  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>
  <button v-text="count"></button>
</div>

<script>
  const app = new MiniVue({
    el: '#app',
    data() {
      return {
        message: 'Hello MiniVue',
        count: 0
      };
    }
  });
  setInterval(() => app.count++, 1000);
</script>

关键点说明

  1. 数据劫持:通过 Object.defineProperty 监听属性变化
  2. 依赖收集:在 getter 中收集依赖,setter 中触发更新
  3. 模板编译:解析 DOM 节点,处理插值和指令
  4. 观察者模式:Watcher 作为桥梁连接数据变更和视图更新

此实现省略了虚拟 DOM、组件系统等复杂功能,但完整展示了 Vue 的响应式核心原理。

实现简易vue

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

相关文章

vue实现下载暂停

vue实现下载暂停

Vue实现下载暂停功能 在Vue中实现下载暂停功能,通常需要结合XMLHttpRequest或Fetch API的AbortController来控制请求中断。以下是具体实现方法: 使用XMLHtt…

vue实现公告

vue实现公告

Vue 实现公告功能的方法 公告功能通常需要实现滚动展示、自动切换或固定显示的效果。以下是几种常见的实现方式: 使用 marquee 标签实现滚动公告 <template> <…

vue实现rtc

vue实现rtc

Vue 实现 RTC 的步骤 安装依赖 在 Vue 项目中安装 WebRTC 相关依赖,如 simple-peer 或 peerjs,用于简化 WebRTC 的实现。 运行以下命令安装 simple-…

vue实现treeview

vue实现treeview

Vue 实现 TreeView 的方法 使用递归组件实现 TreeView 递归组件是 Vue 中实现 TreeView 的常见方式。通过组件调用自身,可以轻松处理嵌套的树形结构数据。 <te…

vue cli 实现

vue cli 实现

Vue CLI 实现步骤 安装 Vue CLI 确保 Node.js 版本在 8.9 或以上。通过 npm 全局安装 Vue CLI: npm install -g @vue/cli 创建新项目 使…

vue拼图实现

vue拼图实现

实现 Vue 拼图游戏的方法 使用 Vue 组件和动态数据绑定 创建一个 Vue 组件来管理拼图的状态和逻辑。通过 v-for 动态渲染拼图块,利用 v-bind 绑定样式和位置。拼图块的数据可以存储…