Blog>
Snippets

Proxies and reactivity internals

Delve into how Vue.js uses proxies for reactivity by creating a simple reactive system from scratch to understand the underlying concepts.
<div id='app'>
    <h1>{{ title }}</h1>
    <p>{{ message }}</p>
</div>
HTML structure for our reactive example. Bindings for `title` and `message` will be reactive.
const app = document.querySelector('#app');
Select the element where our reactive system will be demonstrated.
const data = {
    title: 'Hello, Proxy!',
    message: 'Reactivity is cool'
};
Define the initial state of our reactive data.
const render = () => {
    app.innerHTML = `<h1>${reactive.title}</h1>
    <p>${reactive.message}</p>`;
};
Create a render function that will update the DOM with the latest `reactive` state.
const reactiveHandler = {
    set(target, prop, value) {
        if (value !== target[prop]) {
            target[prop] = value;
            render();
        }
        return true;
    }
};
Define a Proxy handler to intercept set operations and trigger a re-render when data changes.
const reactive = new Proxy(data, reactiveHandler);
Create a reactive proxy of our data object, applying the handler defined earlier.
window.onload = () => {
    render();

    // Simulation of reactive state changes after 2 seconds
    setTimeout(() => {
        reactive.title = 'Updated Title';
        reactive.message = 'Reactivity using Proxies';
    }, 2000);
};
On window load, render the initial state. Then demonstrate reactivity by updating the reactive state after 2 seconds.
body {
    font-family: 'Arial', sans-serif;
}
h1 {
    color: #333;
}
p {
    color: #666;
}
Basic CSS for styling the example.