当前位置:首页 > VUE

js 实现vue

2026-01-13 05:08:26VUE

Vue.js 的基本实现

在 JavaScript 中实现 Vue.js 的核心功能,可以通过数据绑定、响应式系统和虚拟 DOM 来实现。以下是实现 Vue.js 核心功能的简化版本。

数据响应式系统

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

class Observer {
  constructor(data) {
    this.data = 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) {
    this.walk(val); // 递归监听嵌套对象
    const dep = new Dep();
    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(); // 通知更新
      }
    });
  }
}

依赖收集与发布

实现一个简单的依赖收集和发布系统:

js 实现vue

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

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

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

Dep.target = null;

实现 Watcher

Watcher 用于监听数据变化并触发更新:

class Watcher {
  constructor(vm, exp, cb) {
    this.vm = vm;
    this.exp = exp;
    this.cb = cb;
    this.value = this.get();
  }

  get() {
    Dep.target = this;
    const value = this.vm.data[this.exp]; // 触发 getter
    Dep.target = null;
    return value;
  }

  update() {
    const newValue = this.vm.data[this.exp];
    if (newValue !== this.value) {
      this.value = newValue;
      this.cb(newValue);
    }
  }
}

实现 Compiler

Compiler 用于解析模板并绑定数据:

js 实现vue

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.isElementNode(child)) {
        this.compileElement(child);
      } else if (this.isTextNode(child)) {
        this.compileText(child);
      }
      if (child.childNodes && child.childNodes.length) {
        this.compile(child);
      }
    });
  }

  isElementNode(node) {
    return node.nodeType === 1;
  }

  isTextNode(node) {
    return node.nodeType === 3;
  }

  compileElement(node) {
    Array.from(node.attributes).forEach(attr => {
      if (attr.name.startsWith('v-')) {
        const dir = attr.name.substring(2);
        const exp = attr.value;
        this[`${dir}Updater`]?.(node, exp);
      }
    });
  }

  compileText(node) {
    const reg = /\{\{(.+?)\}\}/;
    if (reg.test(node.textContent)) {
      const exp = RegExp.$1.trim();
      this.textUpdater(node, exp);
    }
  }

  textUpdater(node, exp) {
    node.textContent = this.vm.data[exp];
    new Watcher(this.vm, exp, value => {
      node.textContent = value;
    });
  }

  modelUpdater(node, exp) {
    node.value = this.vm.data[exp];
    node.addEventListener('input', e => {
      this.vm.data[exp] = e.target.value;
    });
    new Watcher(this.vm, exp, value => {
      node.value = value;
    });
  }
}

实现 Vue 类

整合以上功能实现一个简单的 Vue 类:

class Vue {
  constructor(options) {
    this.$options = options;
    this.data = options.data;
    new Observer(this.data);
    new Compiler(options.el, this);
    this.proxyData();
  }

  proxyData() {
    Object.keys(this.data).forEach(key => {
      Object.defineProperty(this, key, {
        get() {
          return this.data[key];
        },
        set(newVal) {
          this.data[key] = newVal;
        }
      });
    });
  }
}

使用示例

以下是如何使用这个简化版的 Vue

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

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

关键点说明

  1. 响应式数据:通过 Object.definePropertyProxy 监听数据变化。
  2. 依赖收集:在 getter 中收集依赖,在 setter 中触发更新。
  3. 模板编译:解析模板中的指令和插值表达式,绑定数据和事件。
  4. 虚拟 DOM:更复杂的实现可以引入虚拟 DOM 进行高效更新。

以上是一个简化版的 Vue.js 实现,实际 Vue.js 源码更为复杂,包含虚拟 DOM、组件系统、生命周期等更多功能。

标签: jsvue
分享给朋友:

相关文章

vue实现共享屏幕

vue实现共享屏幕

共享屏幕的基本实现 在Vue中实现共享屏幕功能通常需要结合浏览器的getDisplayMedia API。以下是一个基础实现示例: <template> <div>…

vue实现无线滚动列表

vue实现无线滚动列表

无限滚动列表的实现方法 在Vue中实现无限滚动列表通常结合监听滚动事件和动态加载数据。以下是几种常见方法: 使用自定义指令 创建自定义指令v-infinite-scroll监听滚动事件:…

vue设计与实现目录

vue设计与实现目录

以下是《Vue设计与实现》一书的典型目录结构(根据常见技术书籍及Vue核心内容整理): 响应式系统 响应式数据的基本原理 依赖收集与触发更新 实现简易响应式系统 Proxy与Reflec…

vue公共列表的实现

vue公共列表的实现

实现 Vue 公共列表组件 公共列表组件通常用于展示重复结构的数据,例如商品列表、用户列表等。以下是一个典型的实现方式: 基础实现 创建可复用的列表组件 List.vue: <tem…

vue实现visual

vue实现visual

Vue 实现可视化(Visual)的常见方法 在 Vue 中实现可视化通常涉及数据可视化库的集成,以下是几种主流方案: 使用 ECharts ECharts 是一个强大的 JavaScript 图表…

vue实现slider

vue实现slider

Vue 实现 Slider 组件 使用 Vue 实现 Slider 组件可以通过原生开发或借助第三方库。以下是两种常见方法: 原生实现 Slider 创建一个基础的 Slider 组件,通过 v-m…