我正在构建一个单选按钮,当未选中该按钮时,它会使用默认图片(black-radio.png或white-radio.png,不带选中标记),否则它们会使用black-radio-checked.png或white- radio-checked.png。但是,这个错误确实困扰。我知道可以使用计算属性,但是应该如何解决呢?
var vm = new Vue({
el: '#colorPicker',
data: {
color: 'black',
colors: [
{
name: 'black',
image: 'images/black-radio.png',
image_checked: 'images/black-radio-checked.png'
},
{
name: 'white',
image: 'images/white-radio.png',
image_checked: 'images/white-radio-checked.png'
}
]
}
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js" type="text/javascript"></script>
<div id="colorPicker">
<div class="display-inline-block">
<label :for="colorInfo.name" v-for="(colorInfo, index) in colors">
<input type="radio" name="color" v-model="color" :id="colorInfo.name" class="wireless-headphone-new-input" :value="colorInfo.name"/>
<img :src="'images/' + colorInfo.name + '-radio.png'">
</label>
<div class="confirmation-color capitalize">{{ color }} </div>
</div>
</div>
答案 0 :(得分:1)
每当选中单选按钮时,this.color
的值就会更新。
因此,对v-if
进行color==colorInfo.name
检查,以显示所选单选按钮的image_checked
字段,并使用v-else
显示具有image
字段的其他按钮。
var vm = new Vue({
el: '#colorPicker',
data: {
color: '',
colors: [
{
name: 'black',
image: 'images/black-radio.png',
image_checked: 'images/black-radio-checked.png'
},
{
name: 'white',
image: 'images/white-radio.png',
image_checked: 'images/white-radio-checked.png'
}
]
}
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js" type="text/javascript"></script>
<div id="colorPicker">
<div class="display-inline-block">
<label :for="colorInfo.name" v-for="(colorInfo, index) in colors">
<input type="radio" name="color" v-model="color" :id="colorInfo.name" class="wireless-headphone-new-input" :value="colorInfo.name"/>
<img v-if="color==colorInfo.name" :src="colorInfo.image_checked">
<img v-else :src="colorInfo.image"/>
</label>
<div class="confirmation-color capitalize">{{ color }} </div>
</div>
</div>