[Vuejs]-How to get id from a loop's item in vue.js?

3👍

Pass the joke in the click.

<button v-on:click="upvote(joke)"><i class="fa fa-arrow-down"></i></button>

Use it in the method.

upvote: function(joke) {
  axios.post( this.BASE_URL + "/api/joke/" + joke.id + "/upvote", {
    token: 'secret',
  }).then(function(data){
    console.log(data);
  });
}
👤Bert

2👍

In your v-on:click event pass the joke object: <button v-on:click="upvote(joke)">

You may also need to key your loop like so:

<div class="jokes" v-for="joke in jokes" :key="joke.id">
👤matpie

2👍

Value of the v-on directive not only can be a handle method name but also an inline statement. So you just need to add an argument for the method like following way.

<div class="jokes" v-for="joke in jokes">
  <strong>{{joke.body}}</strong>
  <small>{{joke.upvotes}}</small>
  <button v-on:click="upvote(joke.id)"><i class="fa fa-arrow-down"></i></button>
<div>

And then the method can get id.

methods: {
  upvote: function(id) {
    axios.post(this.BASE_URL + "/api/joke/" + id + "/upvote", {
      token: 'secret',
    }).then(function(data) {
      console.log(data);
    });
  }
},

You can learn more form the API document of Vue

Leave a comment