当前位置:首页 > VUE

手动实现合计vue

2026-03-09 12:44:55VUE

手动实现简易 Vue 数据绑定

实现一个类似 Vue 的数据绑定系统,核心是数据劫持(响应式)和依赖收集(观察者模式)。以下是一个简化版实现:

1. 数据劫持(响应式) 通过 Object.definePropertyProxy 拦截数据变化:

手动实现合计vue

function observe(data) {
  if (!data || typeof data !== 'object') return;
  Object.keys(data).forEach(key => {
    let value = data[key];
    const dep = new Dep(); // 每个属性对应一个依赖管理器
    observe(value); // 递归处理嵌套对象
    Object.defineProperty(data, key, {
      get() {
        Dep.target && dep.addSub(Dep.target); // 收集依赖
        return value;
      },
      set(newVal) {
        if (newVal === value) return;
        value = newVal;
        observe(newVal); // 新值是对象时继续劫持
        dep.notify(); // 通知所有订阅者
      }
    });
  });
}

2. 依赖管理器(Dep) 管理所有依赖(Watcher):

class Dep {
  constructor() {
    this.subs = [];
  }
  addSub(sub) {
    this.subs.push(sub);
  }
  notify() {
    this.subs.forEach(sub => sub.update());
  }
}
Dep.target = null; // 静态属性指向当前Watcher

3. 观察者(Watcher) 连接数据变更与视图更新:

手动实现合计vue

class Watcher {
  constructor(vm, exp, cb) {
    this.vm = vm;
    this.exp = exp;
    this.cb = cb;
    this.value = this.get();
  }
  get() {
    Dep.target = this;
    const value = this.vm._data[this.exp]; // 触发getter收集依赖
    Dep.target = null;
    return value;
  }
  update() {
    const newVal = this.vm._data[this.exp];
    if (newVal !== this.value) {
      this.value = newVal;
      this.cb(newVal);
    }
  }
}

4. 编译器(Compile) 解析模板指令:

function compile(el, vm) {
  vm.$el = document.querySelector(el);
  const fragment = document.createDocumentFragment();
  let child;
  while (child = vm.$el.firstChild) {
    fragment.appendChild(child);
  }
  replace(fragment, vm);
  vm.$el.appendChild(fragment);
}

function replace(node, vm) {
  const reg = /\{\{(.*?)\}\}/g;
  if (node.nodeType === 3) {
    const text = node.textContent;
    if (reg.test(text)) {
      const exp = RegExp.$1.trim();
      node.textContent = text.replace(reg, vm._data[exp]);
      new Watcher(vm, exp, val => {
        node.textContent = text.replace(reg, val);
      });
    }
    return;
  }
  if (node.nodeType === 1 && node.tagName === 'INPUT') {
    const attrs = Array.from(node.attributes);
    attrs.forEach(attr => {
      if (attr.name === 'v-model') {
        const exp = attr.value;
        node.value = vm._data[exp];
        new Watcher(vm, exp, val => {
          node.value = val;
        });
        node.addEventListener('input', e => {
          vm._data[exp] = e.target.value;
        });
      }
    });
  }
  Array.from(node.childNodes).forEach(child => replace(child, vm));
}

5. 主类实现

class MyVue {
  constructor(options) {
    this._data = options.data;
    observe(this._data);
    compile(options.el, this);
  }
}

使用示例

<div id="app">
  <input v-model="message">
  <p>{{ message }}</p>
</div>

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

关键点说明

  • 数据劫持:通过 Object.defineProperty 拦截属性的读取和修改
  • 依赖收集:在 getter 中收集依赖(Watcher),在 setter 中触发更新
  • 观察者模式:Watcher 作为观察者,Dep 作为被观察者
  • 模板编译:通过正则匹配模板中的 {{}} 和指令(如 v-model

这个实现省略了 Vue 的虚拟 DOM、组件系统等复杂功能,但包含了响应式系统的核心原理。现代 Vue 3 改用 Proxy 实现响应式,但核心思想仍保持一致。

标签: vue
分享给朋友:

相关文章

vue实现拼音搜索

vue实现拼音搜索

实现拼音搜索的基本思路 拼音搜索的核心是将中文转换为拼音,并在用户输入拼音时匹配对应的中文内容。Vue中可以通过集成拼音转换库(如pinyin或pinyin-pro)实现这一功能。 安装拼音转换库…

vue SSG实现

vue SSG实现

Vue SSG 实现方法 Vue 的静态站点生成(SSG)可以通过多种工具和框架实现,以下是几种常见的方法: 使用 VuePress VuePress 是一个基于 Vue 的静态站点生成器,适合文档…

vue页面实现

vue页面实现

Vue 页面实现方法 创建 Vue 组件 使用 Vue 单文件组件(SFC)方式创建页面,文件扩展名为 .vue。一个基本的 Vue 组件包含三个部分:模板(template)、脚本(script)和…

vue实现handsontable

vue实现handsontable

Vue 中实现 Handsontable 要在 Vue 项目中集成 Handsontable,可以使用官方提供的 @handsontable/vue 封装库。以下是一个完整的实现步骤。 安装依赖 确…

vue实现picker

vue实现picker

Vue 实现 Picker 组件的方法 在 Vue 中实现 Picker 组件可以通过多种方式完成,以下是几种常见的实现方法: 使用原生 HTML 和 CSS 实现 通过 Vue 的模板和样式绑定,…

vue实现menu

vue实现menu

Vue 实现 Menu 的方法 使用 Element UI 的 Menu 组件 Element UI 提供了现成的 Menu 组件,适合快速实现导航菜单。安装 Element UI 后,可以直接使用…