Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
33
rated 0 times [  38] [ 5]  / answers: 1 / hits: 73995  / 8 Years ago, tue, september 13, 2016, 12:00:00

I have a posts list component and a post component.



I pass a method to call from the posts list to the post component, so when a button is click it will be called.



But I want to pass the post id when this function is clicked



Code:





let PostsFeed = Vue.extend({
data: function () {
return {
posts: [....]
}
},
template: `
<div>
<post v-for=post in posts :clicked=clicked />
</div>
`,
methods: {
clicked: function(id) {
alert(id);
}
}
}

let Post = Vue.extend({
props: ['clicked'],
data: function () {
return {}
},
template: `
<div>
<button @click=clicked />
</div>
`
}





as you can see in Post component you have a click that runs a method he got from a prop, I want to add a variable to that method.



How do you do that?


More From » vue.js

 Answers
4

Normally, the click event handler will receive the event as its first argument, but you can use bind to tell the function what to use for its this and first argument(s):



:clicked=clicked.bind(null, post)


Updated answer: However, it might be more straightforward (and it is more Vue-standard) to have the child emit an event and have the parent handle it.





let Post = Vue.extend({
template: `
<div>
<button @click=clicked>Click me</button>
</div>
`,
methods: {
clicked() {
this.$emit('clicked');
}
}
});

let PostsFeed = Vue.extend({
data: function() {
return {
posts: [1, 2, 3]
}
},
template: `
<div>
<post v-for=post in posts @clicked=clicked(post) />
</div>
`,
methods: {
clicked(id) {
alert(id);
}
},
components: {
post: Post
}
});

new Vue({
el: 'body',
components: {
'post-feed': PostsFeed
}
});

<script src=//cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js></script>
<post-feed></post-feed>




[#60725] Sunday, September 11, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lailab

Total Points: 706
Total Questions: 102
Total Answers: 95

Location: Falkland Islands
Member since Mon, Jul 13, 2020
4 Years ago
;