当前位置:首页 > 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项目中实现打印功能,可以通过以下几种方式实现: 使用window.print()方法 通过调用浏览器的原生打印API实现基础打印功能,适用于简单内容打印。 //…

vue实现博客

vue实现博客

Vue 实现博客的基本步骤 使用 Vue.js 实现一个博客系统可以分为前端和后端两部分。以下是基于 Vue 的前端实现方案,后端可以选择 Node.js、Django 或其他框架。 项目初始化 使…

vue实现数组

vue实现数组

Vue 实现数组操作的方法 在 Vue 中,数组的操作需要特别注意响应式的问题。Vue 提供了一些方法来确保数组的变动能够触发视图更新。 响应式数组方法 Vue 对以下数组方法进行了封装,确保它们能…

vue 实现$(id)

vue 实现$(id)

在 Vue 中实现类似 jQuery 的 $(id) 功能,可以通过以下几种方式操作 DOM 元素: 使用 ref 属性 Vue 推荐使用 ref 属性来直接访问 DOM 元素或组件实例。在模板中为…

vue实现书库

vue实现书库

Vue 实现书库功能 使用 Vue 构建书库功能需要结合前端框架和后端数据管理。以下是实现步骤和关键点: 项目初始化 使用 Vue CLI 或 Vite 初始化项目,安装 Vue Router 和状…

vue实现加载

vue实现加载

Vue 实现加载功能的方法 使用 v-if 或 v-show 控制加载状态 通过数据绑定控制加载动画的显示与隐藏。v-if 会完全移除 DOM 元素,v-show 只是切换 display 属性。…