Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js passing functions to props not working

I have a problem that passing functions to components is not working the way it's specified in the documentation.

This is in my app.js

methods: {
    updateAnswer: function(question) {
        console.log('question: '+question);
    }
}

This is in my html-file:

<multiplechoice class="question counterIncrement counterShow active" id="q2" whenanswered="{{ updateAnswer('1') }}"></multiplechoice>

This is in my components.js file:

props: [
    'whenanswered'
],

ready: function() {
    this.whenanswered();
},

I have already tried this:

props: [
    { name: 'whenanswered', type: Function}
];

but still no luck.

This is in my console when I load the page:

Uncaught TypeError: this.whenanswered is not a function

Any help would be very much appreciated :)

like image 405
thijsdemaa Avatar asked Jun 30 '15 07:06

thijsdemaa


People also ask

Can I pass a function as a prop in Vue?

While you can pass a function as a prop, this is almost always a bad idea. Instead, there is probably a feature of Vue that is designed exactly to solve your problem. If you keep reading you'll see what I mean. Join 11,067 other Vue devs and get exclusive tips and insights delivered straight to your inbox, every week.

How do you pass an object as a prop in Vue?

To pass in the properties of an object as props, we can use the v-bind without the argument. Then the properties of post will be passed into blog-post as prop values. The property names are the prop names.

What is $emit in Vue JS?

Vue $emit is a function that lets us emit, or send, custom events from a child component to its parent. In a standard Vue flow, it is the best way to trigger certain events.


1 Answers

You could do this:

<multiplechoice class="question counterIncrement counterShow active" id="q2" :whenanswered="updateAnswer('1')"></multiplechoice>

Without the ':'(same as v-bind) like you did will only send a string and not evaluate. Even with those {{ }}.

But remember that your updateAnswerfunction should return a function. Since your prop will execute updateAnswer('1') and your multiplechoiceactually expects a function that will be executed when it wants.

methods: {
  whenanswered: function(question) { // or whenanswered (question) { for ES6 
    return function () { ... } // or () => {...} for ES6
  }
}
like image 159
Cassio Cabral Avatar answered Sep 22 '22 12:09

Cassio Cabral