当前位置:首页 > VUE

原生加数组实现vue

2026-02-23 08:58:49VUE

原生 JavaScript 加数组实现 Vue 核心功能

使用原生 JavaScript 和数组模拟 Vue 的核心功能(如数据绑定、响应式更新)可以通过以下方式实现:

数据劫持与响应式

通过 Object.definePropertyProxy 监听数据变化,触发更新逻辑:

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

依赖收集与派发更新

实现简单的发布-订阅模式管理依赖:

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

观察者(Watcher)

连接数据与视图的桥梁:

class Watcher {
  constructor(vm, key, cb) {
    this.vm = vm;
    this.key = key;
    this.cb = cb;
    Dep.target = this;
    this.value = vm[key]; // 触发 getter
    Dep.target = null;
  }
  update() {
    const newValue = this.vm[this.key];
    if (newValue !== this.value) {
      this.value = newValue;
      this.cb(newValue);
    }
  }
}

数组方法劫持

重写数组原型方法以实现响应式:

const arrayProto = Array.prototype;
const arrayMethods = Object.create(arrayProto);
['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'].forEach(method => {
  const original = arrayProto[method];
  arrayMethods[method] = function(...args) {
    const result = original.apply(this, args);
    const ob = this.__ob__;
    let inserted;
    if (['push', 'unshift', 'splice'].includes(method)) {
      inserted = args.slice(0, method === 'splice' ? args[1] : args.length);
    }
    if (inserted) ob.observeArray(inserted);
    ob.dep.notify(); // 触发更新
    return result;
  };
});

简易模板编译

通过正则匹配实现模板插值:

function compile(el, vm) {
  vm.$el = document.querySelector(el);
  const fragment = document.createDocumentFragment();
  let child;
  while (child = vm.$el.firstChild) {
    fragment.appendChild(child);
  }
  function replace(frag) {
    Array.from(frag.childNodes).forEach(node => {
      const txt = node.textContent;
      const reg = /\{\{\s*(.*?)\s*\}\}/g;
      if (node.nodeType === 3 && reg.test(txt)) {
        const key = RegExp.$1.trim();
        new Watcher(vm, key, newVal => {
          node.textContent = txt.replace(reg, newVal);
        });
        node.textContent = txt.replace(reg, vm[key]);
      }
      if (node.childNodes && node.childNodes.length) {
        replace(node);
      }
    });
  }
  replace(fragment);
  vm.$el.appendChild(fragment);
}

整合实现

最终组合成简易 Vue 类:

原生加数组实现vue

class Vue {
  constructor(options) {
    this.$options = options;
    this.$data = options.data();
    observe(this.$data);
    Object.keys(this.$data).forEach(key => {
      Object.defineProperty(this, key, {
        get() {
          return this.$data[key];
        },
        set(newVal) {
          this.$data[key] = newVal;
        }
      });
    });
    compile(options.el, this);
  }
}

使用示例

<div id="app">
  {{ message }}
  <div>{{ count }}</div>
</div>

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

这种方法实现了 Vue 最基础的数据响应式、依赖收集和模板编译功能,实际 Vue 的实现还包含虚拟 DOM、组件系统等更复杂的机制。

标签: 数组vue
分享给朋友:

相关文章

vue实现pie

vue实现pie

Vue 实现饼图 在 Vue 中实现饼图通常可以通过第三方图表库(如 ECharts、Chart.js 或 Highcharts)来完成。以下是使用 ECharts 和 Chart.js 的两种常见方…

vue实现vnc

vue实现vnc

Vue 实现 VNC 客户端 在 Vue 项目中实现 VNC 客户端功能,可以通过集成现有的 VNC 客户端库或组件完成。以下是具体实现方法: 安装依赖库 使用 noVNC 或其他 VNC 客户端…

vue 实现分屏

vue 实现分屏

Vue 实现分屏的方法 使用 CSS Flexbox 或 Grid 布局 通过 CSS Flexbox 或 Grid 布局可以轻松实现分屏效果。在 Vue 组件中定义两个或多个区域,并使用 CSS 控…

vue 实现登录

vue 实现登录

Vue 实现登录功能 创建登录表单组件 在 Vue 项目中创建一个登录表单组件(如 Login.vue),包含用户名和密码输入框以及提交按钮。使用 v-model 实现双向数据绑定。 <tem…

vue实现筛选

vue实现筛选

实现筛选功能的基本思路 在Vue中实现筛选功能通常需要结合数据绑定、计算属性和方法。筛选的核心逻辑是根据用户输入的条件过滤原始数据列表,并动态更新显示结果。 数据准备 定义一个数组存储原始数据,另一…

vue 实现赋值

vue 实现赋值

Vue 实现赋值的方法 在 Vue 中,赋值操作通常涉及数据绑定和响应式更新。以下是几种常见的赋值方式: 直接赋值给 data 属性 在 Vue 实例的 data 对象中定义的属性可以直接通过 th…