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

thi*_*maa 7 javascript vue.js

我有一个问题,即将函数传递给组件的方式与文档中指定的方式不同.

这是我的app.js

methods: {
    updateAnswer: function(question) {
        console.log('question: '+question);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是在我的html文件中:

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

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

props: [
    'whenanswered'
],

ready: function() {
    this.whenanswered();
},
Run Code Online (Sandbox Code Playgroud)

我已经尝试过了:

props: [
    { name: 'whenanswered', type: Function}
];
Run Code Online (Sandbox Code Playgroud)

但仍然没有运气.

当我加载页面时,这是在我的控制台中:

Uncaught TypeError: this.whenanswered is not a function
Run Code Online (Sandbox Code Playgroud)

任何帮助将非常感谢:)

cas*_*ral 8

你可以这样做:

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

没有':'(与v-bind相同)就像你所做的那样只发送一个字符串而不进行评估.即使有这些{{ }}.

但请记住,您的updateAnswer函数应该返回一个函数.因为你的prop会执行updateAnswer('1'),你multiplechoice实际上期望一个将在它想要的时候执行的函数.

methods: {
  whenanswered: function(question) { // or whenanswered (question) { for ES6 
    return function () { ... } // or () => {...} for ES6
  }
}
Run Code Online (Sandbox Code Playgroud)