javascript Vue.js 将函数传递给道具不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31132177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:20:30  来源:igfitidea点击:

Vue.js passing functions to props not working

javascriptvue.js

提问by thijsdemaa

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

这是在我的 app.js 中

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

This is in my html-file:

这是在我的 html 文件中:

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

This is in my components.js file:

这是在我的 components.js 文件中:

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

任何帮助将不胜感激:)

回答by cassioscabral

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

如果没有 ':'(与 v-bind 相同),就像你所做的那样只会发送一个字符串而不是评估。即使与那些{{ }}

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.

但请记住,您的updateAnswer函数应该返回一个函数。由于您的道具将执行updateAnswer('1')并且您multiplechoice实际上期望一个将在需要时执行的函数。

methods: {
  whenanswered: function(question) { // or whenanswered (question) { for ES6 
    return function () { ... } // or () => {...} for ES6
  }
}

回答by swift

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.

如果你想调用那个函数。prop 只是一个字符串,而不是一个函数。

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!')
            }
        }
    }
});