Chris
Chris

Reputation: 14260

Use instance method in click handler

I have a Todo class that has a delete method. I would like to use the delete method as an @click handler:

<div v-for="todo in todos">
    <v-btn @click="todo.delete">Delete</v-btn>
</div>

Unfortunately this gives me:

Invalid handler for event "click": got undefined

Upvotes: 1

Views: 65

Answers (1)

nickford
nickford

Reputation: 792

Here's a simple codepen example that shows the core concept working: https://codepen.io/nickforddesign/pen/YYwgKx

The issue is that the items in your todos array don't have the method.

<div class="app">
  <ul>
    <li v-for="todo in todos">
      {{ todo }}
      <button @click="todo.delete">Delete</button>
    </li>
  </ul>
</div>

And the js

new Vue({
  el: '.app',
  data() {
    return {
      todos: [{
        name: '1',
        delete() {
          alert(`delete`)
        }
      },{
        name: '2',
        delete() {
          alert(`delete`)
        }
      }]
    }
  }
})

Upvotes: 1

Related Questions