首先,来看一下单选框的样式:
<div class="option" v-for="(option, ind) in item.surveyQuestionOptionList" :key="ind"> <input :value="option.selectid" type="radio" :id="'option' + item.qid + option.selectid" :name="item.qid" :checked="ind == 0"> <label :for="'option' + item.qid + option.selectid">{{option.selection}}</label> </div>
input[type="radio"] + label{ position: relative; padding-left: 1.5rem; padding-right: 1rem; width: 100%; } input[type="radio"] + label span{ white-space: pre-wrap; } input[type="radio"] + label::after, input[type="radio"] + label::before { /* content: "\a0"; 不换行空格 */ content:""; display: inline-block; vertical-align: middle; width: 0.6rem; height: 0.6rem; margin-right: .4rem; border-radius: 50%; line-height: 1.2rem; padding: 0.3rem; background: -webkit-linear-gradient(45deg, #fff, #e1e2e4); /* Safari 5.1 - 6.0 */ background: -o-linear-gradient(45deg, #fff, #e1e2e4); /* Opera 11.1 - 12.0 */ background: -moz-linear-gradient(45deg, #fff, #e1e2e4); /* Firefox 3.6 - 15 */ background: linear-gradient(45deg, #fff, #e1e2e4); left: 0; top:0.2rem; position: absolute; } input[type="radio"]:checked + label::before { background: #7a4010; background-clip: content-box; padding: 0.3rem; z-index: 9; } input[type="radio"] { position: absolute; clip: rect(0, 0, 0, 0); }
在中间遇到的问题:
① 默认选中input
标签上加入:checked="ind == num"
,num
为你要默认选中的索引,但加上之后还是没有选中,后来发现是v-model
的原因,你把v-model
去掉,checked
就有效果了
v-model
会忽略所有表单元素的value
、checked
、selected
特性的初始值而总是将Vue
实例的数据作为数据来源。你应该通过 JavaScript 在组件的data
选项中声明初始值。
②取值问题
双向绑定,那么问题来了,在①
中,我们为了默认选中吧v-model
去掉了,可以采用点击事件获取选中的值,但是如果在题目数量不确定的时候,你获取值,再改变值就变得比较复杂,于是我的目光又回到了v-model
身上,仔细想一下上面引用,那我们的checked
也用v-model
好了
<input :value="option.selectid" v-model="answerList.answers[index].answer" type="radio" :id="'option' + item.qid + option.selectid" :name="item.qid"> // 解决问题的代码
文章来源: https://blog.csdn.net/rainbow8300/article/details/88679864