Home > Blockchain >  Vue.js: Pass parameter to function in v-for
Vue.js: Pass parameter to function in v-for

Time:12-31

I have a table that loops through book objects and writes out values. I want to add buttons to edit and delete the objects. How do I pass parameters correctly to the methods?

So far I have tried this:

<table >
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">Title</th>
      <th scope="col">Author</th>
      <th scope="col">Genre</th>
      <th scope="col">ISBN</th>
      <th scope="col">UDC</th>
      <th scope="col">Publisher</th>
      <th scope="col">Year Published</th>
      <th scope="col">Shelf Position</th>
      <th scope="col"></th>
      <th scope="col"></th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="(book, i) in books" :key="i">
      <th scope="row">{{   i }}</th>
      <td>{{ book.title }}</td>
      <td>{{ book.author }}</td>
      <td>{{ book.genre }}</td>
      <td>{{ book.isbn }}</td>
      <td>{{ book.udc }}</td>
      <td>{{ book.publisher }}</td>
      <td>{{ book.year_published }}</td>
      <td>{{ book.shelf_position }}</td>
      <td><button type="submit"  v-on:submit="this.edit(book.book_id)">Edit</button></td>
      <td><button type="submit"  onclick="this.delete('{{book.book_id}}')">Delete</button></td>
    </tr>
  </tbody>
</table>

I have tried two different ways both shown above, but it doesn't work. What am I doing wrong?

CodePudding user response:

When referencing methods/data in templates in vue.js, you don't need to use this - you can refer to it directly by name. You should also be using v-on:click to listen for the events. So you can change those buttons to:

<td><button type="submit"   v-on:click="edit(book.book_id)">Edit</button></td>
<td><button type="submit"  v-on:click="delete('{{book.book_id}}')">Delete</button></td>

This should work as long as edit and delete are defined in your component's methods.

CodePudding user response:

Use the click listener without setting type to submit:

<td><button  @click="edit(book.book_id)">Edit</button></td>
<td><button  @click="delete(book.book_id)">Delete</button></td>

Reference: https://vuejs.org/v2/guide/events.html

  • Related