当前位置:首页 > VUE

用js实现vue

2026-01-18 10:35:54VUE

用 JavaScript 实现 Vue 核心功能

Vue.js 是一个渐进式框架,其核心功能包括响应式数据绑定、虚拟 DOM 和组件系统。以下是一个简化版的实现,展示如何用原生 JavaScript 模拟 Vue 的核心机制。

响应式数据系统

通过 Object.definePropertyProxy 实现数据劫持,监听数据变化并触发更新:

class Observer {
  constructor(data) {
    this.observe(data);
  }

  observe(data) {
    if (!data || typeof data !== 'object') return;
    Object.keys(data).forEach(key => {
      this.defineReactive(data, key, data[key]);
    });
  }

  defineReactive(obj, key, value) {
    const dep = new Dep();
    this.observe(value); // 递归监听嵌套对象
    Object.defineProperty(obj, key, {
      get() {
        Dep.target && dep.addSub(Dep.target);
        return value;
      },
      set(newVal) {
        if (newVal === value) return;
        value = newVal;
        dep.notify(); // 触发更新
      }
    });
  }
}

class Dep {
  constructor() {
    this.subs = [];
  }
  addSub(sub) {
    this.subs.push(sub);
  }
  notify() {
    this.subs.forEach(sub => sub.update());
  }
}

编译模板与指令解析

模拟 Vue 的模板编译过程,解析 v-model 等指令:

class Compiler {
  constructor(el, vm) {
    this.$vm = vm;
    this.$el = document.querySelector(el);
    this.compile(this.$el);
  }

  compile(node) {
    Array.from(node.childNodes).forEach(child => {
      if (this.isElement(child)) {
        this.compileElement(child);
      } else if (this.isInterpolation(child)) {
        this.compileText(child);
      }
      if (child.childNodes.length) {
        this.compile(child);
      }
    });
  }

  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) {
    Array.from(node.attributes).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');
  }

  model(node, exp) {
    this.update(node, exp, 'model');
    node.addEventListener('input', e => {
      this.$vm[exp] = e.target.value;
    });
  }

  update(node, exp, dir) {
    const fn = this[`${dir}Updater`];
    fn && fn(node, this.$vm[exp]);
    new Watcher(this.$vm, exp, val => {
      fn && fn(node, val);
    });
  }

  textUpdater(node, value) {
    node.textContent = value;
  }

  modelUpdater(node, value) {
    node.value = value;
  }
}

实现 Watcher

连接响应式数据和视图更新的桥梁:

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]);
  }
}

整合为 MiniVue

将上述模块组合成一个简易 Vue 类:

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>
  <input v-model="message">
</div>

<script>
  const app = new MiniVue({
    el: '#app',
    data() {
      return {
        message: 'Hello MiniVue!'
      };
    }
  });
</script>

关键点说明

  1. 响应式系统:通过数据劫持监听属性变化,使用发布-订阅模式通知依赖更新。
  2. 模板编译:解析 DOM 节点,识别指令和插值表达式,绑定更新函数。
  3. 虚拟 DOM 简化:示例中直接操作真实 DOM,实际 Vue 使用虚拟 DOM 进行高效 diff。
  4. 组件系统:完整实现需支持组件树、生命周期等,此处仅展示核心数据绑定。

以上代码展示了 Vue 的核心原理,实际 Vue.js 的实现更为复杂,包含优化策略、更多指令支持和完整的生命周期管理。

用js实现vue

标签: jsvue
分享给朋友:

相关文章

vue实现多级组件

vue实现多级组件

实现多级组件的基本结构 在Vue中实现多级组件通常涉及父子组件嵌套,通过props向下传递数据,通过$emit向上传递事件。多级组件的核心是递归或动态组件渲染。 <!-- 父组件 Paren…

vue实现防抖节流

vue实现防抖节流

Vue 中实现防抖(Debounce) 防抖的核心是延迟执行函数,在连续触发时取消前一次的调用,只执行最后一次。适用于输入框搜索、窗口大小调整等场景。 方法1:使用 Lodash 的 _.debou…

vue实现RTMP

vue实现RTMP

Vue 中实现 RTMP 流播放 RTMP(Real-Time Messaging Protocol)是一种用于实时音视频流传输的协议。在 Vue 中实现 RTMP 播放通常需要借助第三方库或播放器。…

vue 实现excel

vue 实现excel

Vue 实现 Excel 功能 前端导出 Excel 使用 xlsx 库可以轻松实现前端 Excel 导出功能。安装依赖: npm install xlsx 导出 Excel 示例代码: impo…

vue 实现上传

vue 实现上传

Vue 实现文件上传 使用 Vue 实现文件上传可以通过原生 HTML 的 <input type="file"> 或第三方库(如 axios、vue-upload-component)完…

vue实现滚屏

vue实现滚屏

实现滚屏的基本方法 在Vue中实现滚屏效果可以通过多种方式完成,常见的有原生JavaScript滚动方法、第三方库或CSS动画。以下是几种常见实现方式: 使用window.scrollTo或Elem…