当前位置:首页 > VUE

vue 原理简易实现

2026-01-19 18:41:32VUE

Vue 原理简易实现

Vue 的核心原理包括响应式数据绑定、虚拟 DOM 和模板编译。以下是一个简化版的实现,展示 Vue 的基本工作机制。

响应式数据绑定

通过 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(); // 数据变化时通知依赖更新
      }
    });
  }
}

依赖收集与派发更新

通过 DepWatcher 实现依赖收集和更新派发。

class Dep {
  constructor() {
    this.subs = [];
  }

  addSub(sub) {
    this.subs.push(sub);
  }

  notify() {
    this.subs.forEach(sub => sub.update());
  }
}

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]);
  }
}

虚拟 DOM 与 Diff 算法

简化版的虚拟 DOM 实现,通过比较新旧虚拟 DOM 树来最小化 DOM 操作。

class VNode {
  constructor(tag, data, children, text) {
    this.tag = tag;
    this.data = data;
    this.children = children;
    this.text = text;
  }
}

function patch(oldVnode, vnode) {
  if (!oldVnode) {
    // 首次渲染
    createElm(vnode);
  } else {
    // 更新逻辑
    const isRealElement = oldVnode.nodeType;
    if (isRealElement) {
      // 初次渲染替换真实 DOM
      const parent = oldVnode.parentNode;
      const elm = createElm(vnode);
      parent.insertBefore(elm, oldVnode);
      parent.removeChild(oldVnode);
    } else {
      // Diff 算法简化版
      if (oldVnode.tag !== vnode.tag) {
        // 标签不同直接替换
        oldVnode.el.parentNode.replaceChild(createElm(vnode), oldVnode.el);
      } else {
        // 更新属性
        const el = (vnode.el = oldVnode.el);
        updateProps(el, vnode.data, oldVnode.data);
        // 更新子节点
        patchChildren(el, oldVnode.children, vnode.children);
      }
    }
  }
}

模板编译

将模板字符串转换为渲染函数。

function compile(template) {
  const ast = parse(template); // 解析模板为 AST
  const code = generate(ast); // 生成渲染函数代码
  return new Function(`with(this){return ${code}}`);
}

// 示例 AST 转换(简化版)
function parse(template) {
  const stack = [];
  let root;
  let currentParent;

  parseHTML(template, {
    start(tag, attrs) {
      const element = { tag, attrs, children: [] };
      if (!root) root = element;
      if (currentParent) currentParent.children.push(element);
      stack.push(element);
      currentParent = element;
    },
    end() {
      stack.pop();
      currentParent = stack[stack.length - 1];
    },
    chars(text) {
      currentParent.children.push({ text });
    }
  });

  return root;
}

整合实现

将以上部分整合为一个简易的 Vue 类。

class Vue {
  constructor(options) {
    this.$options = options;
    this._data = options.data();
    new Observer(this._data);
    this._proxyData();
    this.$mount(options.el);
  }

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

  $mount(el) {
    this.$el = document.querySelector(el);
    const updateComponent = () => {
      const vnode = this.$options.render.call(this);
      patch(this._vnode || this.$el, vnode);
      this._vnode = vnode;
    };
    new Watcher(this, updateComponent);
  }
}

使用示例

const app = new Vue({
  el: '#app',
  data() {
    return { message: 'Hello Vue!' };
  },
  render() {
    return h('div', null, this.message);
  }
});

以上代码展示了 Vue 的核心原理简化实现,包括响应式系统、虚拟 DOM 和模板编译。实际 Vue 源码更加复杂,但基本原理与此类似。

vue 原理简易实现

标签: 简易原理
分享给朋友:

相关文章

实现简易vue

实现简易vue

实现简易 Vue 的核心思路 Vue 的核心功能包括数据响应式、模板编译和虚拟 DOM。以下是一个简易实现方案,涵盖核心功能模块。 数据响应式系统 通过 Object.defineProperty…

vue rooter 实现原理

vue rooter 实现原理

Vue Router 实现原理 Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。其核心实现原理包括路由匹配、组件渲染和导航守卫等机制。 路由匹配与动态路由 V…

vue动态组建实现原理

vue动态组建实现原理

Vue动态组件的实现原理 Vue的动态组件主要通过<component>标签和is属性实现,其核心原理涉及以下机制: 动态组件基础语法 <component :is="curren…

vue实现绑卡的原理

vue实现绑卡的原理

Vue实现绑卡的原理 Vue实现绑卡功能通常涉及表单绑定、数据验证、API交互等核心环节。以下是关键实现原理和步骤: 数据双向绑定 使用v-model指令实现表单输入与Vue实例数据的双向绑定。例…

vue 实现原理

vue 实现原理

Vue 实现原理 Vue.js 是一个渐进式 JavaScript 框架,其核心实现原理主要包括响应式系统、虚拟 DOM、模板编译和组件化机制。 响应式系统 Vue 使用 Object.define…

vue动画实现原理

vue动画实现原理

Vue动画实现原理 Vue的动画系统基于CSS过渡和动画,结合Vue的响应式系统,提供声明式的方式管理元素进入/离开的动画效果。核心原理分为以下几个部分: 过渡类名自动应用 Vue在元素插入…