当前位置:首页 > VUE

js 实现vue

2026-01-08 00:55:48VUE

实现 Vue 的核心功能

在 JavaScript 中实现 Vue 的核心功能需要模拟数据绑定、虚拟 DOM 和响应式系统。以下是一个简化版的实现思路:

响应式系统

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

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;

虚拟 DOM 与渲染

实现一个简单的虚拟 DOM 和渲染函数。

class VNode {
  constructor(tag, data, children, text) {
    this.tag = tag;
    this.data = data;
    this.children = children;
    this.text = text;
  }
}

function render(vnode, container) {
  const el = document.createElement(vnode.tag);
  for (const key in vnode.data) {
    el.setAttribute(key, vnode.data[key]);
  }
  if (vnode.text) {
    el.textContent = vnode.text;
  } else if (vnode.children) {
    vnode.children.forEach(child => {
      render(child, el);
    });
  }
  container.appendChild(el);
}

组件系统

实现一个简单的组件系统,将模板、数据和方法封装在一起。

class Vue {
  constructor(options) {
    this.$options = options;
    this._data = options.data();
    new Observer(this._data);
    this.compile(options.el);
  }

  compile(el) {
    const element = document.querySelector(el);
    this.compileNode(element);
  }

  compileNode(node) {
    if (node.nodeType === 1) {
      Array.from(node.attributes).forEach(attr => {
        if (attr.name.startsWith('v-')) {
          const dir = attr.name.substring(2);
          this[dir](node, attr.value);
        }
      });
      node.childNodes.forEach(child => this.compileNode(child));
    } else if (node.nodeType === 3) {
      const reg = /\{\{(.*?)\}\}/g;
      const text = node.textContent;
      if (reg.test(text)) {
        const key = RegExp.$1.trim();
        new Watcher(this._data, key, (newVal) => {
          node.textContent = text.replace(reg, newVal);
        });
        node.textContent = text.replace(reg, this._data[key]);
      }
    }
  }

  model(node, key) {
    node.value = this._data[key];
    new Watcher(this._data, key, (newVal) => {
      node.value = newVal;
    });
    node.addEventListener('input', (e) => {
      this._data[key] = e.target.value;
    });
  }
}

Watcher 实现

Watcher 用于连接响应式数据和视图更新。

js 实现vue

class Watcher {
  constructor(data, key, cb) {
    this.cb = cb;
    Dep.target = this;
    this.value = data[key];
    Dep.target = null;
  }

  update() {
    this.cb(this.value);
  }
}

使用示例

<div id="app">
  <input v-model="message">
  <p>{{ message }}</p>
</div>

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

实现要点

  • 数据劫持:使用 Object.definePropertyProxy 监听数据变化。
  • 依赖收集:通过 DepWatcher 管理依赖关系。
  • 模板编译:解析模板中的指令和插值表达式,绑定数据和事件。
  • 虚拟 DOM:简化版的虚拟 DOM 实现,用于高效更新视图。

以上代码展示了 Vue 的核心功能实现,包括响应式数据、模板编译和虚拟 DOM。实际 Vue 的实现更为复杂,包含更多优化和功能。

标签: jsvue
分享给朋友:

相关文章

vue实现选区创建

vue实现选区创建

Vue 实现选区创建的方法 在 Vue 中实现选区创建通常涉及 DOM 操作和事件处理。以下是几种常见的方法: 使用原生 DOM API 通过 window.getSelection() 和 Ran…

js实现vue

js实现vue

Vue.js 的基本实现方法 在 JavaScript 中实现 Vue.js 的功能,可以通过直接引入 Vue 库或使用现代构建工具(如 Vite 或 Webpack)。以下是几种常见的实现方式:…

vue实现类别

vue实现类别

Vue 实现类别的几种方法 在 Vue 中实现类别功能可以通过多种方式完成,以下是一些常见的方法: 使用 v-bind:class 动态绑定类名 通过对象语法或数组语法动态绑定类名,根据条件添加或移…

vue实现模块

vue实现模块

Vue 实现模块化的方法 Vue 支持多种模块化开发方式,可以根据项目需求选择适合的方案。 使用单文件组件(SFC) 单文件组件是 Vue 最常用的模块化方式,将模板、脚本和样式封装在一个 .vue…

vue实现博客

vue实现博客

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

vue nexttick实现

vue nexttick实现

Vue 中 nextTick 的实现原理 Vue 的 nextTick 是一个用于在下次 DOM 更新循环结束之后执行延迟回调的方法。它的核心实现依赖于 JavaScript 的事件循环机制。 基本…