当前位置:首页 > 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(); // 通知更新
      }
    });
  }
}

依赖收集与发布

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

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 用于解析模板并绑定数据:

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、组件系统、生命周期等更多功能。

js 实现vue

标签: jsvue
分享给朋友:

相关文章

vue实现共享屏幕

vue实现共享屏幕

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

项目基于vue实现

项目基于vue实现

基于Vue实现项目的关键方法 搭建基础环境 安装Node.js和npm/yarn,确保开发环境具备运行Vue的能力。通过Vue CLI快速初始化项目结构,选择所需配置(如Babel、Router、Vu…

vue实现前端注册

vue实现前端注册

Vue 实现前端注册功能 注册表单设计 使用 Vue 的模板语法创建注册表单,包含用户名、邮箱、密码和确认密码字段。表单需绑定 v-model 实现双向数据绑定。 <template>…

vue实现tab换行

vue实现tab换行

Vue实现Tab切换的常见方法 使用Vue实现Tab切换功能可以通过多种方式完成,以下是几种常见的方法: 动态组件结合v-if或v-show 通过v-if或v-show控制不同Tab内容的显示与隐…

vue怎么实现页面返回

vue怎么实现页面返回

Vue 实现页面返回的方法 在 Vue 中实现页面返回功能,可以通过以下几种方式完成,具体取决于项目使用的路由模式和技术栈。 使用 Vue Router 的编程式导航 通过 this.$router…

vue查看更多怎么实现

vue查看更多怎么实现

实现 Vue 的“查看更多”功能 数据截取与显示控制 通过 v-if 或 v-show 控制内容的显示与隐藏。初始状态下只显示部分内容,点击“查看更多”后展开完整内容。 <template&…