You can use v-model
to bind a Boolean variable to realize the function of selecting all multiple selection boxes. Specific steps are as follows:
-
Define an array in
data
to store the state of all items that need to be selected. -
Use the directive in the template
v-for
to loop through each select box and bind the state of each select box to the corresponding item in the array. -
Add a select all checkbox to the template and bind its state to a boolean variable.
-
Use to
watch
monitor the state change of the selected check box. When the state of the selected check box changes, traverse each item in the array and set its state to the state of the selected check box.
Sample code:
<template>
<div>
<input type="checkbox" v-model="selectAll"> 全选
<div v-for="(item, index) in items" :key="index">
<input type="checkbox" v-model="item.checked"> {
{
item.label }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
selectAll: false,
items: [
{
label: '选项1', checked: false },
{
label: '选项2', checked: false },
{
label: '选项3', checked: false },
],
};
},
watch: {
selectAll(val) {
this.items.forEach(item => {
item.checked = val;
});
},
},
};
</script>
In the above code, we define a selectAll
variable to represent the state of the check box, and an items
array to store the state of all items that need to be selected. In the template, use v-for
the directive to loop through each select box and bind the state of each select box to the corresponding item in the array. At the same time, a select all checkbox is added and its state is bound to selectAll
the variable.
In watch
, monitor selectAll
the change of the variable, when its state changes, traverse items
each item in the array, and set its state to the selectAll
state of to realize the all-selection function.
The result display: