问题
So I have several checkboxes
and two of them should function like radiobuttons
meaning that if I click on one, the other one should become disabled and vice versa (I know I can do it using radiobuttons
but I need to use checkboxes
). What's the best way to do it?
Here is my code for those two checkboxes
:
<v-checkbox label="Check1" value="Check1" v-model="Check1" ></v-checkbox>
<v-checkbox label="Check2" value="Check2" v-model="Check2" ></v-checkbox>
回答1:
Try to handle the @change
event which will update the Check1
and Check2
as follows :
<v-checkbox label="Check1" value="Check1" v-model="Check1" @change="Check2=!Check1"></v-checkbox>
<v-checkbox label="Check2" value="Check2" v-model="Check2" @change="Check1=!Check2"></v-checkbox>
you could check this pen
回答2:
Your two values aren't independent of each other; one defines the other. So you should only have one data
item, and the other can be a settable computed.
data: {
Check1: true
},
computed: {
Check2: {
get() {
return !this.Check1;
},
set(newValue) {
this.Check1 = !newValue;
}
}
}
If you did want them to be not completely linked – say you want to be able to have both of them off – you would make two data
items and have a watch
on each that turns the other off when this one is turned on.
data: {
Check1: true,
Check2: false
},
watch: {
Check1(nv) { if (nv) { this.Check2 = false; } },
Check2(nv) { if (nv) { this.Check1 = false; } }
}
来源:https://stackoverflow.com/questions/53733952/disabling-a-checkbox-by-checking-another-checkbox-in-vuetify