Implementing a List Rendering with v-for Directive
Show how to render a list of items using the v-for directive in a component template and reflect changes in the VDOM.
<div id="app">
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
HTML template with v-for directive to render a list within a Vue app.
<script src="https://unpkg.com/vue@2.6.14/dist/vue.js"></script>
<script>
new Vue({
el: '#app',
data: {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
]
}
});
</script>
The JavaScript part using Vue to provide data for the list, creating Vue instance with items array.
<style>
ul {
list-style-type: none;
padding: 0;
}
li {
margin: 0.5rem 0;
padding: 0.5rem;
background-color: #f0f0f0;
border-radius: 4px;
}
</style>
The CSS to style the list elements.