简体   繁体   中英

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

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 class="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" class="btn btn-secondary" v-on:submit="this.edit(book.book_id)">Edit</button></td>
      <td><button type="submit" class="btn btn-secondary" 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?

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" class="btn btn-secondary"  v-on:click="edit(book.book_id)">Edit</button></td>
<td><button type="submit" class="btn btn-secondary" 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.

Use the click listener without setting type to submit :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM