Reputation: 2711
I have a v-for loop where I loop through some data returned from my api and set the key equal to the id of the object in the api. Now I want to create a click event that gets the v-bind:key value of the clicked element. This is so that I can use it to find all the data for this object in my posts[] array. But I don't know if it is possible to do this, if so how?
Here's my code;
<template>
<div id="summary_section">
<h2>Summary</h2>
<div id="summary_board">
<div class="column">
<div class="head">
<h3>Opportunities</h3>
</div>
<div class="body">
<div class="post"
v-for="post in posts"
v-bind:key="post._id"
v-on:click="getPostData"
>
<p>{{ post._id }}</p>
<p class="company">{{ post.company_name }}</p>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return{
posts: []
};
},
created() {
axios.get('http://localhost:5000/')
.then(res => {
console.log(res.data);
const data = res.data;
this.posts = data;
})
.catch(error => console.log(error));
},
methods: {
UpdatePosts() {
axios.get('http://localhost:5000/')
.then(res => {
// console.log(res);
const data = res.data;
this.posts = data;
})
.catch(error => console.log(error));
},
getPostData(event) {
console.log(event);
}
}
}
</script>
Upvotes: 2
Views: 2885
Reputation: 73966
You can update your template like:
v-on:click="getPostData(post._id)"
and then access this value like:
getPostData(id) {
console.log(id);
}
Also, @click
is just shorthand for v-on:click
directive, so you can also use that if you like:
@click="getPostData(post._id)"
Upvotes: 4
Reputation: 1
Just pass that id
as parameter inside the event click handler as follows :
v-on:click="getPostData($event,post._id)"
the method handler :
getPostData(event,id) {
console.log(event,id);
}
if you don't need the event object you could do that like :
v-on:click="getPostData(post._id)"
and
getPostData(id) {
console.log(id);
}
Upvotes: 5