当前位置:首页 > VUE

原生js实现vue

2026-03-08 10:20:15VUE

使用原生 JavaScript 实现 Vue 的核心功能

Vue 的核心功能包括数据绑定、模板渲染、响应式系统和事件处理。以下是实现这些功能的关键步骤。

数据绑定与响应式系统

通过 Object.definePropertyProxy 实现数据的响应式监听。以下是一个基于 Object.defineProperty 的简单实现:

function defineReactive(obj, key, val) {
  const dep = new Dep();
  Object.defineProperty(obj, key, {
    get() {
      if (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());
  }
}

模板编译与渲染

实现一个简单的模板编译器,将模板中的插值表达式(如 {{data}})替换为实际数据:

原生js实现vue

class Compiler {
  constructor(el, vm) {
    this.$vm = vm;
    this.$el = document.querySelector(el);
    if (this.$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 && child.childNodes.length > 0) {
        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;
  }
}

观察者模式

实现 Watcher 类,用于监听数据变化并更新视图:

class Watcher {
  constructor(vm, exp, cb) {
    this.$vm = vm;
    this.exp = exp;
    this.cb = cb;
    Dep.target = this;
    this.value = vm[exp];
    Dep.target = null;
  }
  update() {
    const oldValue = this.value;
    this.value = this.$vm[this.exp];
    this.cb.call(this.$vm, this.value, oldValue);
  }
}

主框架整合

将上述功能整合为一个简单的 Vue 类:

原生js实现vue

class Vue {
  constructor(options) {
    this.$options = options;
    this.$data = options.data();
    this.observe(this.$data);
    new Compiler(options.el, this);
  }
  observe(data) {
    Object.keys(data).forEach(key => {
      defineReactive(this, key, data[key]);
    });
  }
}

使用方法

以下是如何使用这个简易 Vue 实现的示例:

<div id="app">
  <p>{{ message }}</p>
</div>

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

实现双向绑定

扩展功能以实现 v-model 双向绑定:

// 在 Compiler 类中添加对 v-model 的处理
compileElement(node) {
  const attrs = node.attributes;
  Array.from(attrs).forEach(attr => {
    const attrName = attr.name;
    const exp = attr.value;
    if (attrName === 'v-model') {
      this.bindModel(node, exp);
    }
  });
}
bindModel(node, exp) {
  node.value = this.$vm[exp];
  node.addEventListener('input', e => {
    this.$vm[exp] = e.target.value;
  });
  new Watcher(this.$vm, exp, value => {
    node.value = value;
  });
}

注意事项

  1. 这只是 Vue 核心功能的简化实现,实际 Vue 源码更复杂,包含虚拟 DOM、组件系统等。
  2. 现代 Vue 3 使用 Proxy 代替 Object.defineProperty 实现响应式系统,性能更好。
  3. 完整实现还需处理数组变化检测、生命周期钩子、计算属性等功能。

标签: jsvue
分享给朋友:

相关文章

vue实现翻译

vue实现翻译

Vue 实现翻译功能的方法 使用 i18n 插件实现多语言切换 安装 vue-i18n 插件: npm install vue-i18n 创建语言资源文件(如 en.json 和 zh.json):…

vue实现机制

vue实现机制

Vue 实现机制的核心原理 Vue.js 的核心实现机制主要基于响应式系统、虚拟 DOM 和组件化设计。以下是关键实现细节: 响应式系统 Vue 通过 Object.defineProperty(V…

vue 实现筛选

vue 实现筛选

实现筛选功能的基本方法 在Vue中实现筛选功能通常涉及以下几个核心步骤: 数据绑定与筛选逻辑 使用v-model绑定筛选条件到Vue实例的数据属性,结合计算属性实现动态筛选: data() {…

vue实现tap

vue实现tap

Vue 实现 Tap 事件 在移动端开发中,Tap 事件比 Click 事件更常用,因为 Click 事件有 300ms 延迟。以下是几种在 Vue 中实现 Tap 事件的方法。 使用第三方库 安装…

vue实现换页

vue实现换页

Vue实现页面切换的方法 在Vue中实现页面切换通常可以通过Vue Router来完成。Vue Router是Vue.js官方的路由管理器,用于构建单页面应用(SPA)。以下是几种常见的实现方式:…

mvvm实现vue

mvvm实现vue

MVVM 模式在 Vue 中的实现 MVVM(Model-View-ViewModel)是一种前端架构模式,Vue 的设计灵感来源于此。以下是 MVVM 在 Vue 中的核心实现方式: 数据绑定(M…