我正在尝试将单选按钮添加到我的代码中。除了一件事之外,一切都很好。当我使用 v-for 循环创建 radio 时,不会检查默认 radio 。如果我把它放在 for 循环之外,它就会起作用。
我已经尝试过这个:-
:checked="index == 1"
还有这个(正如一些答案中所建议的):-
:checked="{ index == 1 }"
但他们都不适合我。
下面是我的模板片段:-
<div class="props-data">
<!-- <input type="radio" :checked="currentStep==1"> -->
<span v-for="(shape, index) in availableShapes" v-if="currentStep==1">
<div>
<input type="radio" :id="shape" :value="shape" v-model="selectedShape" :checked="index == 1">
<label :for="shape">{{shape}}</label>
</div>
</span>
</div>
注意:- steps-container 是创建 Vue 实例的主要父类。
下面是我的js代码:-
window.onload = function(){
new Vue({
el: '#steps-container',
data: function() {
return {
currentStep: 1,
availableShapes: ['Rectangle','Circle','Square','Ellipse'],
selectedShape: undefined
};
},
methods: {
cancel: function(){
this.currentStep = 1;
jQuery('#main-action').text('Go to step '+ (this.currentStep+1));
},
nextStep: function(){
if( this.currentStep == 2 ){
jQuery('#main-action').text('Startover');
this.currentStep++;
}
else{
if( this.currentStep == 3 ){
this.currentStep = 1;
}
else{
this.currentStep++;
}
jQuery('#main-action').text('Go to step '+ (this.currentStep+1));
}
}
},
mounted: function(){
},
updated: function(){
}
});
}
任何帮助将不胜感激。
最佳答案
您无需设置 checked
吸引你自己。通过使用v-model="selectedShape"
您已将所有 radio 输入链接到 selectedShape
.
您已经可以通过控制selectedShape
的值来控制检查的属性。 .
所以设置初始值selectedShape
为默认值,默认勾选。
<input type="radio" :id="shape" :value="shape" v-model="selectedShape">
(删除:checked="index == 1"
)
data: function() {
return {
//...
selectedShape: "THE DEFAULT VALUE"
};
},
关于javascript - 如果与 v-for 一起使用,则无法设置默认输入单选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49487859/