专业的编程技术博客社区

网站首页 > 博客文章 正文

React、Vue 和 Angular 如何工作:从零开始的实现

baijin 2025-04-06 13:28:40 博客文章 19 ℃ 0 评论

在前端开发中,React、Vue 和 Angular 是三种最流行的框架。虽然它们在实现细节上各有不同,但核心原则相似。

特性

Angular

React

Vue

官方网站

angular.io

reactjs.org

vuejs.org

初始发布

2010

2013

2014

当前版本

13.x

17.x

3.x

许可证

MIT

MIT

MIT

使用者

Google, Wix

Facebook, Uber

Alibaba, GitLab

本文将通过简单的示例代码,深入探讨这三个框架的工作原理。

1. 响应式系统

Vue 的实现

Vue 的响应式系统使用了 Proxy,当数据变化时,自动通知订阅的视图更新。以下是一个简单的 Vue 实现示例:

function reactive(obj) {
    const listeners = new Set();

    const proxy = new Proxy(obj, {
        get(target, property) {
            if (typeof target[property] === 'object') {
                return reactive(target[property]);
            }
            return target[property];
        },
        set(target, property, value) {
            target[property] = value;
            listeners.forEach(fn => fn());
            return true;
        }
    });

    proxy.subscribe = function (fn) {
        listeners.add(fn);
    };

    return proxy;
}

React 的实现

React 使用 hooks 实现状态管理,利用组件内的状态存储和更新:

function useState(initialValue) {
    const state = [initialValue, setState];
    function setState(value) {
        state[0] = value;
        currentComponent.render();
    }
    return state;
}

Angular 的实现

Angular 的响应式系统类似于 Vue,利用代理和监听器来处理数据变化:

function reactive(data) {
    const listeners = [];
    const proxy = new Proxy(data, {
        set(target, property, value) {
            target[property] = value;
            listeners.forEach(listener => listener());
            return true;
        }
    });

    proxy.subscribe = function (listener) {
        listeners.push(listener);
    };

    return proxy;
}

2. 组件化

Vue 组件

Vue 组件的创建和渲染非常简单,以下是一个 Vue 组件示例:

class Component {
    constructor(options) {
        this.template = options.template;
        this.data = reactive(options.data());
        this.methods = options.methods;

        this.data.subscribe(this.render.bind(this));
        this.render();
    }

    render() {
        const el = document.getElementById('root');
        el.innerHTML = this.template.replace(/{{\s*(\w+)\s*}}/g, (_, key) => this.data[key]);
        this.applyMethods(el);
    }

    applyMethods(el) {
        Object.keys(this.methods).forEach(methodName => {
            const matches = el.querySelectorAll(`[data-action="${methodName}"]`);
            matches.forEach(match => {
                match.onclick = this.methods[methodName].bind(this.data);
            });
        });
    }
}

React 组件

React 组件使用函数和状态钩子来管理渲染和状态:

const MyComponent = createComponent(function () {
    const [count, setCount] = useState(0);

    return h('div', { className: 'my-component' },
        h('p', { className: 'message' }, `Count: ${count}`),
        h('button', { onclick: () => setCount(count + 1) }, 'Increment')
    );
});

Angular 组件

Angular 组件通过控制器将数据和方法结合:

const MyController = {
    data() {
        return { count: 0 };
    },
    methods: {
        increment() {
            this.count++;
        },
        decrement() {
            this.count--;
        }
    }
};

3. DOM 更新

Vue 的 DOM 更新

Vue 会在数据变化时重新渲染视图,而不是手动操作 DOM。数据的变化直接影响 DOM 的显示。

React 的虚拟 DOM

React 使用虚拟 DOM,通过 diff 算法高效更新真实 DOM:

function patch(parent, patchObj) {
    // 实现更新逻辑
}

Angular 的编译和更新

Angular 在每次数据变化时,重新编译 DOM:

function compile(element) {
    // 绑定和更新 DOM 元素
}

结论

无论是 Vue、React 还是 Angular,这三者都实现了响应式系统、组件化结构和高效的 DOM 更新机制。

通过理解它们的基本实现原理,开发者能够更好地利用这些框架构建现代 web 应用。

每种框架都有其独特的特点和优势,选择最适合项目需求的工具至关重要。

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表