Blog>
Snippets

Basic v-for Usage

Show how to render a list of items onto the DOM using Vue.js's v-for directive.
<div id="app">
  <ul>
    <!-- Use v-for to render a list of items -->
    <li v-for="item in items" :key="item.id">
      {{ item.name }}
    </li>
  </ul>
</div>
This is a template snippet using Vue.js's v-for directive. It defines an unordered list where each list item is rendered by iterating over an array called 'items'. Each item's name is displayed in a list element and Vue.js's special ':key' attribute is used to provide each element a unique identifier, thus optimizing DOM updates.
new Vue({
  el: '#app',
  data: {
    items: [
      { id: 1, name: 'Item 1' },
      { id: 2, name: 'Item 2' },
      { id: 3, name: 'Item 3' }
    ]
  }
});
This JavaScript code snippet uses Vue.js to initialize a new Vue instance, binding it to the DOM element with id 'app'. It also defines a 'data' object that contains an 'items' array. Each element in this array is an object with an 'id' and a 'name', which corresponds to the data structure expected in the template's v-for loop.