当前位置:首页 > VUE

js 实现vue

2026-02-10 12:35:18VUE

在 JavaScript 中实现 Vue 的核心功能(如响应式数据、模板渲染等)可以通过以下方式完成。以下是一个简化版的实现示例,涵盖基础功能:

响应式数据实现

使用 Object.definePropertyProxy 实现数据劫持,监听数据变化:

js 实现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();
      }
    });
  }
}

依赖收集系统

实现简单的发布-订阅模式来管理依赖:

class Dep {
  constructor() {
    this.subs = [];
  }

  addSub(sub) {
    this.subs.push(sub);
  }

  notify() {
    this.subs.forEach(sub => sub.update());
  }
}

Dep.target = null;

编译模板

实现基础模板编译,将 {{}} 语法替换为数据:

js 实现vue

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

  compile(node) {
    const childNodes = node.childNodes;
    Array.from(childNodes).forEach(child => {
      if (this.isElement(child)) {
        this.compileElement(child);
      } else if (this.isInterpolation(child)) {
        this.compileText(child);
      }
      if (child.childNodes) {
        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');
  }

  update(node, exp, dir) {
    const updater = dir + 'Updater';
    this[updater] && this[updater](node, this.$vm[exp]);
    new Watcher(this.$vm, exp, value => {
      this[updater] && this[updater](node, value);
    });
  }

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

观察者实现

创建观察者来连接响应式数据和视图更新:

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 Vue {
  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>
</div>

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

  setTimeout(() => {
    app.message = 'Updated!';
  }, 1000);
</script>

注意事项

  • 以上实现仅为简化版,Vue 实际源码更复杂,包含虚拟 DOM、组件系统等
  • 现代 Vue 3 使用 Proxy 代替 Object.defineProperty 实现响应式
  • 完整实现需处理数组变化、指令系统、生命周期等更多功能
  • 建议参考 Vue 源码学习完整实现细节

标签: jsvue
分享给朋友:

相关文章

vue实现缩放

vue实现缩放

Vue 实现缩放的方法 在 Vue 中实现缩放功能可以通过多种方式完成,以下是一些常见的方法: 使用 CSS transform 属性 通过 CSS 的 transform: scale() 属性可…

vue实现muli

vue实现muli

Vue 实现多语言(i18n)支持 在 Vue 项目中实现多语言(i18n)功能,通常使用 vue-i18n 插件。以下是具体实现步骤: 安装 vue-i18n npm install vue-i…

vue实现 toast

vue实现 toast

Vue 实现 Toast 组件 在 Vue 中实现 Toast 组件可以通过多种方式完成,以下是几种常见的方法: 使用全局组件和事件总线 创建一个全局的 Toast 组件,并通过事件总线或 Vue…

vue实现list

vue实现list

Vue 实现列表渲染 在 Vue 中,可以使用 v-for 指令来渲染列表。v-for 指令基于一个数组或对象来渲染一个列表,可以遍历数组或对象的属性。 基本列表渲染 <template>…

vue实现slot

vue实现slot

Vue 中的 Slot 实现方法 Vue 的 slot 是一种内容分发机制,允许父组件向子组件插入内容。以下是几种常见的 Slot 实现方式: 默认 Slot 子组件通过 <slot>…

vue实现拖动

vue实现拖动

Vue实现拖动的常用方法 在Vue中实现拖动功能通常需要结合HTML5的拖放API或第三方库。以下是几种常见实现方式: 使用HTML5原生拖放API HTML5提供了原生拖放API,可以通过drag…