Rendering a list of VNodes with v-for
Shows how to use the `v-for` directive to render a list of VNodes and track each node's identity with the `key` attribute.
// Import the Vue library
import Vue from 'vue';
// Define a new Vue component
Vue.component('vnode-list', {
// The 'items' prop represents the array of data
props: ['items'],
render(h) {
// Use the 'v-for' directive to render each item
// The 'key' attribute provides a unique identifier for tracking each VNode
return h('ul', {}, this.items.map((item, index) => h('li', { key: item.id }, item.text)));
}
});
// Usage example with Vue instance
new Vue({
el: '#app',
data: {
// Sample data for the list
list: [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{ id: 3, text: 'Item 3' }
]
}
});
This piece of code defines a Vue component that renders a list of items using the 'v-for' directive within the render function. Each item is given a unique 'key' based on its 'id' to help Vue track the list for efficient updates. It also includes an example Vue instance that initializes the component with sample data and mounts it to the '#app' element.