问题
I have 5 v-swtich components, called A, B, C, D and E.
Here is what I want to achieve:
If I switch on A, then D and E must automatically switch on, and the user must not be able to switch D and E off unless if he switches off A.
If A is not switched on, the the user can switch on D or E.
- If the user switches on any combinations where D and E appear (for example: (C, D, E), (C, D, E, B), (B, D, E) ) then A must be automatically switched on, and the user must not switch off D and E until he switches off A.
Here is some code to start with:
<div id="app">
<v-app id="inspire">
<v-container fluid>
<p>{{ people }}</p>
<v-switch v-model="people" label="A" value="A"></v-switch>
<v-switch v-model="people" label="B" value="B"></v-switch>
<v-switch v-model="people" label="C" value="C"></v-switch>
<v-switch v-model="people" label="D" value="D"></v-switch>
<v-switch v-model="people" label="E" value="E"></v-switch>
</v-container>
</v-app>
</div>
The JS code:
new Vue({
el: '#app',
data () {
return {
people: []
}
}
})
If I set the value
prop to A, D and E components, whenever I toggle one of them on or off, the 2 others follow (and that is not what I want to do).
I really appreciate any help regarding this.
回答1:
Is this what you wanted? codepen (or perhaps cleaner: codepen)
<v-switch v-for="(person, i) in people"
:key="person.label"
v-model="people[i].value"
:label="people[i].label"
:disabled="people[i].disabled"
></v-switch>
people: [
{ value: false, label: "A", disabled: false },
//...
created() {
// here we watch for D and E changes, and set A to true if both D and E are ON
this.$watch(
vm => vm.people[3].value && vm.people[4].value, (newVal, oldVal) => {
if(newVal) {
this.people[0].value = true;
}
});
},
watch: {
"people.0.value"(newVal) {
if (newVal) { // if A is turned ON
// turn D and E on, and disable them
this.people[3].value = true;
this.people[4].value = true;
this.people[3].disabled = true;
this.people[4].disabled = true;
} else { // if A is turned OFF
// enable D and E
this.people[3].disabled = false;
this.people[4].disabled = false;
}
}
}
Not sure what else to add. Basically watch for changes and react on them.
回答2:
Using computed getters/setters provides a method of backing view properties with logic. Rather than directly linking to data
, Vue will call the computed methods with whatever logic has been supplied.
The second part of the problem is disabling buttons. This can be accomplished with the v-switch disabled property:
<v-switch
:disabled="computedPropertyToDisable"
v-model="computedPropertyForValue"
...
</v-switch>
来源:https://stackoverflow.com/questions/52459582/how-to-control-these-components