Vue.js pass function as prop and make child call it with data

Tzook Bar Noy picture Tzook Bar Noy · Sep 13, 2016 · Viewed 48.5k times · Source

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:

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?

Answer

Roy J picture Roy J · Sep 13, 2016

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>