当前位置:首页 > 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 项目中创建一个登录组件,通常命名为 Login.vue。该组件包含用户名和密码输入框以及提交按钮。 <template> &l…

vue实现飘窗原理

vue实现飘窗原理

vue实现飘窗原理 飘窗效果通常指在页面上悬浮显示的弹窗或通知,跟随页面滚动或固定在某个位置。Vue实现这一效果主要依赖组件化开发、CSS定位和动态数据绑定。 组件结构设计 创建一个独立的Vue组件…

实现vue模版

实现vue模版

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

vue实现新闻

vue实现新闻

Vue 实现新闻功能 使用 Vue 实现新闻功能通常涉及新闻列表展示、新闻详情页、分类筛选等模块。以下是实现的基本思路和代码示例。 新闻列表展示 通过 Vue 组件展示新闻列表,通常使用 v-for…

vue router 实现

vue router 实现

Vue Router 的实现 Vue Router 是 Vue.js 的官方路由管理器,用于构建单页面应用(SPA)。以下是 Vue Router 的核心实现方式。 安装 Vue Router 通过…

vue实现拍照

vue实现拍照

Vue实现拍照功能 在Vue中实现拍照功能通常需要结合浏览器的MediaDevices API和Canvas元素。以下是具体实现方法: 安装依赖(可选) 如果需要更简单的封装,可以安装vue-web…