【发布时间】:2020-12-11 10:05:37
【问题描述】:
目前我正在从 youtube 学习 vue.js。有一些逻辑可以判断一个 html 元素是否应该具有哪个类。
在本教程中,将逻辑添加到 methods 中可以正常工作,但如果我将逻辑添加到 computed 中。我无法将其用作属性值
有解决方法吗?只是不知何故我觉得我应该将它添加到 computed 所以我尝试了它并且错误显示 [Vue warn]: Error in render: "TypeError: Cannot read property 'answerItemClass' of undefined" 我理解错误
我将它放入computed 可能是错误的,只是不知何故出现了这个问题,想知道如果将来我真的想放入computed 而不是methods,那么会有一个简单的解决方法吗?
下面的html示例
<b-list-group-item
v-for="(answer, index) in answers"
v-html="answer"
:key="index"
:class="this.answerItemClass(index)"
:disabled="answered"
@click="selectAnswer(index)"
>
</b-list-group-item>
脚本,添加到 computed 而不是 methods
computed: {
answerItemClass(index) {
let result = ''
if (this.selectedIndex === index) result = 'selected';
if ((this.answered) &&
(this.correctAnswerIndex === index)
) result = 'correct';
if ((this.answered) &&
(this.selectedIndex === index) &&
(this.correctAnswerIndex !== index)
) result = 'incorrect';
return result;
},
}
提前感谢您的任何建议和建议。
【问题讨论】:
-
html模板中不需要
this
标签: javascript vue.js methods computed-properties