Blog>
Snippets

Handling Events on List Items

Show how to listen for events on elements rendered with v-for and access the item index and content.
new Vue({
  el: '#app',
  data: {
    items: ['Apple', 'Banana', 'Cherry']
  },
  methods: {
    handleItemClick(index, itemContent) {
      console.log(`Item ${index + 1}: ${itemContent} was clicked.`);
      // Handle the click event for the item here
    }
  }
});
This initializes a Vue instance targeting the element with id 'app'. It sets up a data object with an array of items and defines a method to handle click events on list items. The method logs the index and content of the clicked item.
<div id="app">
  <ul>
    <li v-for="(item, index) in items" @click="handleItemClick(index, item)">
      {{ item }}
    </li>
  </ul>
</div>
This HTML snippet works with the Vue instance. It uses the v-for directive to render list items and attaches a click event listener to each item. When a list item is clicked, the 'handleItemClick' method is called with the current index and item content.