当前位置:首页 > VUE

手动实现合计vue

2026-02-18 00:02:41VUE

手动实现 Vue 的核心功能

实现一个简易的 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 节点,解析指令和插值表达式,并建立与数据的关联。

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

  compile(el) {
    const childNodes = el.childNodes;
    Array.from(childNodes).forEach(node => {
      if (this.isElement(node)) {
        this.compileElement(node);
      } else if (this.isInterpolation(node)) {
        this.compileText(node);
      }
      if (node.childNodes && node.childNodes.length > 0) {
        this.compile(node);
      }
    });
  }

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

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

  compileElement(node) {
    const attrs = node.attributes;
    Array.from(attrs).forEach(attr => {
      const attrName = attr.name;
      const exp = attr.value;
      if (this.isDirective(attrName)) {
        const dir = attrName.substring(2);
        this[dir] && this[dir](node, exp);
      }
    });
  }

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

  isDirective(attr) {
    return attr.startsWith('v-');
  }

  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[key];
    Dep.target = null;
  }

  update() {
    this.cb.call(this.$vm, this.$vm[this.key]);
  }
}

整合功能

将以上功能整合到一个 Vue 类中,完成简易实现。

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

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

使用示例

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

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

以上代码实现了一个简易的 Vue 框架,包含数据响应式、模板编译和依赖更新等核心功能。可以根据需求进一步扩展指令和功能。

手动实现合计vue

标签: vue
分享给朋友:

相关文章

vue设计与实现下载

vue设计与实现下载

vue设计与实现电子书下载 《Vue.js设计与实现》是一本深入解析Vue.js框架原理的书籍,由霍春阳(HcySunYang)撰写。以下是获取该资源的常见途径: 正版购买渠道 京东、…

vue实现store

vue实现store

Vue 实现 Store 在 Vue 中,可以通过 Vuex 或 Pinia 实现全局状态管理(Store)。以下是两种主流方案的实现方法。 使用 Vuex 实现 Store Vuex 是 Vue…

vue实现ai

vue实现ai

Vue 实现 AI 功能 Vue.js 可以通过集成第三方 AI 服务或本地 AI 模型来实现 AI 功能。以下是几种常见的方法: 集成第三方 AI API 使用 Vue 调用如 OpenAI、Go…

vue实现跑车

vue实现跑车

Vue 实现跑车动画效果 使用 Vue 结合 CSS 动画可以实现跑车在屏幕上移动的效果。以下是一个完整的实现方案: 创建 Vue 组件结构 <template> <div c…

vue实现图库

vue实现图库

Vue 实现图库的基本方法 使用 Vue 实现图库功能可以通过多种方式完成,以下是一些常见的方法和实现步骤。 使用 Vue 和第三方库(如 Vue Gallery) 安装 vue-gallery 或…

vue实现slider

vue实现slider

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