How to run a method using v-for in vue.js?

Member

by gilbert , in category: Javascript , 2 months ago

How to run a method using v-for in vue.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lottie , a month ago

@gilbert 

To run a method using v-for in Vue.js, you can use the v-on directive to bind a method to an event such as click or change. Here's an example:

  1. Define your method in the methods object of your Vue component:
1
2
3
4
5
6
methods: {
  myMethod: function(item) {
    console.log('You clicked on ' + item);
    // Add your logic here
  }
}


  1. Use the v-for directive to iterate over a list of items and bind the method to an event using v-on:
1
2
3
4
5
<ul>
  <li v-for="item in items" v-on:click="myMethod(item)">
    {{ item }}
  </li>
</ul>


In this example, when a user clicks on a list item, the myMethod function will be called with the item as a parameter. You can then perform any desired logic inside the method.