当前位置:首页 > 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 类中,完成简易实现。

手动实现合计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 实现滑动输入条 使用原生 HTML5 input range 实现 在 Vue 模板中直接使用 <input type="range">,通过 v-model 绑定数据:…

vue实现轮询

vue实现轮询

实现轮询的基本方法 在Vue中实现轮询可以通过setInterval或setTimeout配合递归调用完成。轮询通常用于定期向服务器请求数据更新。 使用setInterval的简单示例: data…

vue 实现轮播

vue 实现轮播

Vue 实现轮播的方法 使用第三方库(如 Swiper) 安装 Swiper 库: npm install swiper 在 Vue 组件中引入 Swiper: <template>…

vue实现上传

vue实现上传

Vue 文件上传实现方法 使用 Vue 实现文件上传可以通过原生 HTML5 的 <input type="file"> 元素结合 Vue 的事件处理和数据绑定来实现。 基础实现步骤…

vue实现swipe

vue实现swipe

Vue实现Swipe功能的方法 使用第三方库(推荐) Vue生态中有多个成熟的轮播/滑动组件库,例如vue-awesome-swiper或swiper/vue。以下是基于swiper/vue的实现示例…

mvvm实现vue

mvvm实现vue

MVVM 模式在 Vue 中的实现 MVVM(Model-View-ViewModel)是一种前端架构模式,Vue 的设计灵感来源于此。以下是 MVVM 在 Vue 中的核心实现方式: 数据绑定(M…