当前位置:首页 > VUE

实现简易vue

2026-01-07 18:13:03VUE

实现简易 Vue 的核心思路

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

数据响应式系统

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

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

依赖收集与发布订阅

实现 Dep(依赖收集器)和 Watcher(观察者):

实现简易vue

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实现分页的方法 使用Element UI的分页组件 Element UI提供了现成的分页组件el-pagination,可以快速实现分页功能。 <template> &…

vue实现增删改

vue实现增删改

Vue 实现增删改查功能 Vue.js 是一个流行的前端框架,用于构建用户界面。以下是使用 Vue.js 实现增删改查(CRUD)功能的方法。 数据初始化 在 Vue 实例的 data 中初始化一个…

vue实现年历

vue实现年历

Vue 实现年历的方法 使用 Vue 实现年历可以通过组件化开发方式,结合日期计算和动态渲染完成。以下是两种常见的实现方式: 基于原生 Vue 的日历组件 创建 Calendar.vue 组件文件…

vue实现多选联动

vue实现多选联动

vue实现多选联动的方法 使用v-model绑定数组 在Vue中,可以通过v-model绑定一个数组来实现多选联动。当复选框被选中或取消选中时,数组会自动更新。 <template>…

vue实现路由导航

vue实现路由导航

路由导航的实现方式 在Vue中,路由导航主要通过Vue Router实现。Vue Router是Vue.js官方的路由管理器,用于构建单页面应用(SPA)。 基本路由配置 安装Vue Router后…

vue实现sql操作

vue实现sql操作

在Vue中实现SQL操作通常需要结合后端服务或本地数据库技术,因为前端JavaScript无法直接连接SQL数据库。以下是几种常见的实现方式: 通过API与后端交互 Vue前端通过HTTP请求(如a…