当前位置:首页 > 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实现store

vue实现store

Vue 实现 Store 在 Vue 中,可以通过 Vuex 或 Pinia 实现全局状态管理(Store)。以下是两种主流方案的实现方法。 使用 Vuex 实现 Store Vuex 是 Vue…

vue实现handsontable

vue实现handsontable

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

vue实现Siri

vue实现Siri

Vue 实现 Siri 风格语音交互 实现类似 Siri 的语音交互功能需要结合语音识别、语音合成和前端交互逻辑。Vue 作为前端框架,可以很好地管理这些功能的交互状态。 语音识别集成 使用 Web…

vue实现分步

vue实现分步

Vue 实现分步功能 在 Vue 中实现分步功能可以通过多种方式完成,以下是几种常见的方法: 使用动态组件 通过动态组件切换不同的步骤内容,结合 v-if 或 component 标签实现分步逻辑。…

vue实现tabs

vue实现tabs

Vue实现Tabs组件的方法 使用动态组件和v-for指令 在Vue中创建Tabs组件可以通过动态组件和v-for指令实现。定义一个包含tab标题和内容的数组,使用v-for渲染tab标题,并通过点击…

vue实现音乐

vue实现音乐

Vue实现音乐播放功能 使用Vue实现音乐播放功能可以通过多种方式完成,以下是几种常见的实现方法: 使用HTML5 Audio API 在Vue组件中直接使用HTML5的Audio对象来控制音乐播放…