thijsdemaa
thijsdemaa

Reputation: 324

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 :)

Upvotes: 7

Views: 13267

Answers (2)

Cassio Cabral
Cassio Cabral

Reputation: 2682

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
  }
}

Upvotes: 8

swift
swift

Reputation: 1108

A fiddle would help, but basically, you need:

methods: {
    whenanswered: function(question) {
        ...
    }
}

if you wanna call that function. A prop is just a string, not a function.

Example:

<div id="app">
    Loading...
    <data-table on-load="{{onChildLoaded}}"></data-table>
</div>

new Vue({
  el: "#app",
    methods: {
        onChildLoaded: function (msg) {
            console.log(msg);
        }
    },
    components: {
        'data-table': {
            template: 'Loaded',    
            props: ['onLoad'],
            ready: function () {
                this.onLoad('the child has now finished loading!')
            }
        }
    }
});

Upvotes: 0

Related Questions