当前位置:首页 > VUE

javascript实现vue

2026-01-12 23:46:15VUE

使用JavaScript实现Vue核心功能

通过原生JavaScript可以模拟Vue的核心功能,如数据绑定、指令系统和虚拟DOM。以下是实现Vue响应式系统的关键步骤:

数据劫持(响应式系统)

javascript实现vue

class Vue {
  constructor(options) {
    this.$data = options.data();
    this.observe(this.$data);
  }

  observe(data) {
    if (!data || typeof data !== 'object') return;
    Object.keys(data).forEach(key => {
      this.defineReactive(data, key, data[key]);
    });
  }

  defineReactive(obj, key, val) {
    this.observe(val);
    const dep = new Dep();
    Object.defineProperty(obj, key, {
      get() {
        Dep.target && dep.addSub(Dep.target);
        return val;
      },
      set(newVal) {
        if (newVal === val) return;
        val = newVal;
        dep.notify();
      }
    });
  }
}

依赖收集系统

javascript实现vue

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

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

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

Dep.target = null;

编译器实现

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

  compile(el) {
    el.childNodes.forEach(node => {
      if (node.nodeType === 1) {
        this.compileElement(node);
        if (node.childNodes.length) {
          this.compile(node);
        }
      } else if (this.isInterpolation(node)) {
        this.compileText(node);
      }
    });
  }

  isInterpolation(node) {
    return node.nodeType === 3 && /\{\{(.*)\}\}/.test(node.textContent);
  }

  compileText(node) {
    const exp = RegExp.$1.trim();
    this.update(node, exp, 'text');
  }

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

  text(node, exp) {
    this.update(node, exp, 'text');
  }

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

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

Watcher实现

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]);
  }
}

基本使用方法

const vm = new Vue({
  el: '#app',
  data() {
    return {
      message: 'Hello Vue',
      count: 0
    };
  }
});

// HTML结构示例
/*
<div id="app">
  <p>{{ message }}</p>
  <button v-text="count"></button>
</div>
*/

实现双向数据绑定

// 在Compiler类中添加model指令处理
model(node, exp) {
  this.update(node, exp, 'model');
  node.addEventListener('input', e => {
    this.$vm[exp] = e.target.value;
  });
}

modelUpdater(node, value) {
  node.value = value;
}

实现计算属性

class Vue {
  constructor(options) {
    // ...原有代码
    this.initComputed(options.computed);
  }

  initComputed(computed) {
    if (!computed) return;
    Object.keys(computed).forEach(key => {
      Object.defineProperty(this, key, {
        get: typeof computed[key] === 'function' 
          ? computed[key].bind(this)
          : computed[key].get.bind(this)
      });
    });
  }
}

这个实现包含了Vue最核心的响应式系统、模板编译和依赖追踪功能。实际Vue.js的实现更加复杂,包含虚拟DOM、组件系统、生命周期管理等更多特性,但这个示例展示了基本原理。

标签: javascriptvue
分享给朋友:

相关文章

vue实现列表显示

vue实现列表显示

Vue 实现列表显示的方法 在 Vue 中实现列表显示通常使用 v-for 指令,结合数组或对象数据渲染动态列表。以下是几种常见的实现方式。 基本列表渲染 通过 v-for 指令遍历数组,动态生成列…

vue实现钟表

vue实现钟表

使用 Vue 实现动态钟表 以下是一个基于 Vue 3 的动态钟表实现方案,包含时分秒指针和数字时间显示。 模板部分 <template> <div class="clock-…

vue 实现pdf

vue 实现pdf

在Vue中实现PDF功能 在Vue项目中实现PDF功能通常涉及PDF生成、预览或下载。以下是几种常见实现方式: 使用vue-pdf库预览PDF 安装依赖: npm install vue-pdf…

vue实现键盘

vue实现键盘

Vue 实现键盘功能 在Vue中实现键盘功能通常涉及监听键盘事件、处理输入以及渲染虚拟键盘界面。以下是几种常见的实现方式: 监听键盘事件 通过@keydown或@keyup指令监听键盘事件,适用于需…

vue实现cs

vue实现cs

Vue 实现 CS(Client-Side)渲染的常见方法 Vue.js 是一个用于构建用户界面的渐进式框架,默认采用客户端渲染(CSR)。以下是几种常见的实现方式: 使用 Vue CLI 创建项目…

vue实现看板

vue实现看板

Vue 实现看板功能 使用 Vue 实现看板功能可以通过组件化开发、状态管理和拖拽库结合完成。以下是一个完整的实现方案: 基础项目结构 src/ ├── components/ │ ├── Ka…