当前位置:首页 > 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 中登录实现逻辑 前端实现逻辑 表单验证 使用 Vue 的表单验证库(如 VeeValidate)或自定义验证规则,确保用户输入的账号和密码符合要求。例如,检查邮箱格式、密码长度等。 发送登录…

vue实现点击

vue实现点击

实现点击事件的基本方法 在Vue中实现点击事件可以通过v-on指令或@简写方式绑定。以下是常见的点击事件绑定方法: <template> <button v-on:click=…

vue实现贴图

vue实现贴图

Vue 实现贴图功能 在Vue中实现贴图功能通常涉及将图片动态添加到指定位置或元素上。以下是几种常见实现方式: 使用v-bind动态绑定图片 通过数据驱动的方式动态更换图片源: <templ…

实现vue模版

实现vue模版

Vue 模板的基本结构 Vue 模板基于 HTML 语法,通过 Vue 的指令和插值实现动态渲染。以下是一个基础模板示例: <template> <div id="…

django vue实现

django vue实现

Django与Vue.js整合实现方案 Django作为后端框架与Vue.js作为前端框架的整合,可以通过以下方式实现: 分离式开发 前后端完全分离,Django仅提供API接口,Vue.js通过a…

vue插槽实现

vue插槽实现

插槽的基本概念 Vue插槽(Slot)是一种内容分发机制,允许父组件向子组件传递模板片段,子组件通过<slot>标签定义接收位置。插槽的核心作用是增强组件的灵活性和复用性。 默认插槽 子…