【发布时间】:2018-12-29 01:14:47
【问题描述】:
有没有办法在 Vue.js 中编写三元运算符来设置单选按钮的状态?现在我有 v-if/v-else-if/v-else 在标签内显示 3 种类型的单选按钮。我想以某种方式使用三元运算符来设置checked 或disabled 的属性,具体取决于当前输入是正确的、不正确的还是简单的答案。我还计划使用三元运算符来设置输入的类,但这并不重要,除非我可以根据答案是正确的、不正确的还是普通的,在每个输入上设置检查/禁用属性回答。
<label class="form-check-label"
v-bind:style="
(!question.Correct && question.AnswerGiven==(index+1)) ? wrongAnswer
: (!question.Correct && question.CorrectAnswer == (index+1)) ? rightgAnswer
: plainAnswer">
<!-- Wrong Answer -->
<input type="radio" v-if="!question.Correct && question.AnswerGiven==(index+1)"
v-on:input="changed(question.Question.ID,index)"
v-bind:class="{wrongAnswerInput: !question.Correct && question.AnswerGiven==(index+1)}"
class="form-check-input"
:value="index"
:name="question.Question.ID"
checked>
<!-- Correct Answer -->
<input type="radio" v-else-if="!question.Correct && question.CorrectAnswer == (index+1)"
v-on:input="changed(question.Question.ID,index)"
v-bind:class="{correctAnswerInput: !question.Correct && question.CorrectAnswer == (index+1)}"
class="form-check-input"
:value="index"
:name="question.Question.TestSharedID"
checked>
<!-- Plain Answer -->
<input type="radio" v-else
v-on:input="changed(question.Question.ID,index)"
class="form-check-input"
:value="index"
:name="question.Question.TestSharedID"
disabled>
{{answer}}
</label>
以下更新代码 所以这就是我将它重构为.. 但不确定我是否已经盯着它太久了,但是为每个输入元素分配了正确的类,但现在它没有禁用正常输入。现在在加载时,它正在预先检查我想要的不正确答案,但它没有禁用正常输入,也没有预先检查正确答案。
<label class="form-check-label"
v-bind:style="
(!question.Correct && question.AnswerGiven==(index+1)) ? wrongAnswer
: (!question.Correct && question.CorrectAnswer == (index+1)) ? rightgAnswer
: plainAnswer">
<!-- Wrong Answer -->
<input type="radio"
v-on:input="changed(question.Question.ID,index)"
v-bind:class="
(!question.Correct && question.AnswerGiven == (index+1)) ? wrongAnswerInput
: (!question.Correct && question.CorrectAnswer == (index+1)) ? correctAnswerInput
: plainAnswer"
class="form-check-input"
:value="index"
:name="
(!question.Correct && question.AnswerGiven == (index+1)) ? question.Question.ID
: (!question.Correct && question.CorrectAnswer == (index+1)) ? question.Question.TestSharedID
: question.Question.TestSharedID"
:checked="isChecked"
:disabled="isDisabled">
{{answer}}
</label>
而计算出来的属性如下……
isDisabled() {
let questions = this.reviewPanel.Questions
for (let i = 0; i < questions.length; i++) {
for (let j = 0; j < questions[i].Question.AnswerChoices.length; j++) {
if(questions[i].Correct) {
return true
}
}
}
},
isChecked() {
let questions = this.reviewPanel.Questions
for (let i = 0; i < questions.length; i++) {
for (let j = 0; j < questions[i].Question.AnswerChoices.length; j++) {
if(!questions[i].Correct && questions[i].CorrectAnswer == (j+1) || !questions[i].Correct && questions[i].AnswerGiven == (j+1)) {
return true
}
}
}
}
【问题讨论】:
标签: javascript vue.js vuejs2 vue-component ternary-operator