gpt4 book ai didi

javascript - Vue.js 将函数传递给 Prop 不起作用

转载 作者:数据小太阳 更新时间:2023-10-29 04:38:29 25 4
gpt4 key购买 nike

我遇到一个问题,就是将函数传递给组件并没有按照文档中指定的方式工作。

这是在我的 app.js 中

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

这是在我的 html 文件中:

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

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

props: [
'whenanswered'
],

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

我已经试过了:

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

但仍然没有运气。

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

Uncaught TypeError: this.whenanswered is not a function

非常感谢任何帮助:)

最佳答案

你可以这样做:

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

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

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

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

关于javascript - Vue.js 将函数传递给 Prop 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31132177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com