How to pass a parameter to a method in Vue.js

in Code Write a comment

Learn how to pass arguments to Vue.js functions/methods. In Vue.js we can use v-on directive to trigger JavaScript functions when DOM changes.

For example, you can make Vue.js listen to v-on:click directive on HTML <a> or <button> tags and call a method if user clicks on those tags.

You can also pass a parameter to Vue.js methods.

Passing an argument to a Vue.js method

In the example below, we have a list of items (it can be a list of books, products, anything). This list is rendered from an array of objects using a v-for loop.

Vue.js

new Vue({
  el: "#app",
  data: {
    items: [
      { id: 1, text: "Item 1" },
      { id: 2, text: "Item 2" },
      { id: 3, text: "Item 3" }
    ]
  },
  methods: {
  	removeItem(itemId) {
      this.items = this.items.filter((obj) => {
      	return obj.id !== itemId;
      })
    }
  }
})

Each list item has a remove button next to it. Our goal is to pass item id to the removeItem() method that will remove this item from the array.

We can do that by adding item.id inside the method, like so:

<a href="#" @click="removeItem(item.id)">Remove</a>

HTML

<div id="app">
  <h2>Items:</h2>
  <ol>
    <li v-for="item in items">
      {{ item.text }} <a href="#" @click="removeItem(item.id)">Remove</a>
    </li>
  </ol>
</div>

Will output to:

You can also pass an additional $event parameter to access event object. Make sure to edit your method as well.

<a href="#" @click="removeItem($event, item.id)">Remove</a>

If you find this post useful, please let me know in the comments below. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/pass-parameter-to-method-vue-js

PS: Make sure you check other Vue.js tutorials, e.g. how to bind img src in Vue.js.

Write a Comment

Comment