Reputation: 14834
I have a loop like this:
<div class="jokes" v-for="joke in jokes">
<strong>{{joke.body}}</strong>
<small>{{joke.upvotes}}</small>
<button v-on:click="upvote"><i class="fa fa-arrow-down"></i></button>
<div>
I need to get joke.id
so that I can post it to backend and increment the votes.
The method should be something like this:
methods: {
upvote: function(e) {
axios.post( this.BASE_URL + "/api/joke/" + this.joke.id + "/upvote", {
token: 'secret',
}).then(function(data){
console.log(data);
});
}
},
How can I achieve this?
Upvotes: 0
Views: 1822
Reputation: 334
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
Upvotes: 2
Reputation: 17512
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">
Upvotes: 2
Reputation: 82439
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);
});
}
Upvotes: 3