VDOM Patching Process
Demonstrate the patching process of the VDOM in Vue.js by updating a list and highlighting which nodes are patched versus those that are not.
<div id='app'></div>
HTML Div container where our Vue app will be mounted.
<script src='https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js'></script>
Include the Vue.js library for our example.
<style>
.patched { color: red; }
</style>
CSS style to highlight patched nodes in the list.
<script>
new Vue({
el: '#app',
data: {
items: ['Item 1', 'Item 2', 'Item 3']
},
mounted() {
setTimeout(() => {
this.items[1] = 'Item 2 (updated)'; // Update the second item
this.items.push('Item 4'); // Add a new item
}, 2000);
},
render(h) {
const listItems = this.items.map((item, index) => {
return h('li', { key: item, class: this.isPatched(index) ? 'patched' : '' }, item);
});
return h('ul', listItems);
},
methods: {
isPatched(index) {
// Custom logic to determine if a node has been patched.
// In a real VDOM patching scenario, this would not be hard-coded.
return index === 1 || index === this.items.length - 1;
}
}
});
</script>
The Vue instance controlling our app. It includes the item list data and a function to simulate item updates. The `render` function creates virtual DOM nodes for each item, applying the 'patched' class to nodes that are updated or added. The `isPatched` method simulates the patching recognition process.