当前位置:首页 > 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 实现动态菜单的常见方法 基于路由配置生成菜单 Vue Router 的路由配置可以天然转化为菜单结构,适合权限与路由绑定的系统: // router/index.js const rout…

vue公共列表的实现

vue公共列表的实现

实现 Vue 公共列表组件 公共列表组件通常用于展示重复结构的数据,例如商品列表、用户列表等。以下是一个典型的实现方式: 基础实现 创建可复用的列表组件 List.vue: <templ…

vue实现飘窗原理

vue实现飘窗原理

vue实现飘窗原理 飘窗效果通常指在页面上悬浮显示的弹窗或通知,跟随页面滚动或固定在某个位置。Vue实现这一效果主要依赖组件化开发、CSS定位和动态数据绑定。 组件结构设计 创建一个独立的Vue组件…

vue实现绑卡的原理

vue实现绑卡的原理

Vue 实现绑卡的原理 Vue 实现绑卡功能通常涉及前端表单处理、数据绑定、验证以及和后端 API 的交互。以下是实现绑卡功能的核心原理和步骤: 数据绑定与表单处理 Vue 通过 v-model…

vue实现密码框的包

vue实现密码框的包

Vue 密码框实现方案 在 Vue 中实现密码框功能,可以通过原生 HTML 结合 Vue 指令或使用第三方组件库完成。以下是几种常见方案: 原生 HTML + Vue 双向绑定 <temp…

vue请求实现进度条

vue请求实现进度条

实现请求进度条的方法 在Vue中实现请求进度条可以通过多种方式完成,常见的有使用第三方库如axios结合nprogress或自定义进度条组件。以下是几种实现方法: 使用axios和nprogress…