当前位置:首页 > 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组件

实现vue组件

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

vue实现换行

vue实现换行

Vue 中实现换行的几种方法 在 Vue 中实现换行可以通过多种方式,具体取决于使用场景和需求。以下是常见的几种方法: 使用 HTML 的 <br> 标签 在模板中直接使用 <br…

vue实现表白

vue实现表白

Vue 实现表白页面 使用 Vue 可以快速创建一个动态、交互式的表白页面。以下是一个简单的实现方案: 基础结构 创建一个 Vue 项目或单文件组件,包含以下核心部分: <template&…

vue 实现单选

vue 实现单选

使用 v-model 绑定单选值 在 Vue 中,可以通过 v-model 绑定单选按钮的值。定义一个响应式数据(如 selectedOption),并将其与单选按钮的 value 属性关联。…

vue实现mouseout

vue实现mouseout

Vue 实现 mouseout 事件的方法 在 Vue 中实现 mouseout 事件可以通过多种方式完成,以下是几种常见的方法: 使用 v-on 指令 Vue 提供了 v-on 指令(或简写为 @…

实现vue cli

实现vue cli

安装 Vue CLI 确保系统中已安装 Node.js(版本建议 12.x 或更高)。通过 npm 全局安装 Vue CLI: npm install -g @vue/cli 安装完成后验证版本:…