Vue: select all multiple select boxes

You can use v-modelto bind a Boolean variable to realize the function of selecting all multiple selection boxes. Specific steps are as follows:

  1. Define an array in datato store the state of all items that need to be selected.

  2. Use the directive in the template v-forto loop through each select box and bind the state of each select box to the corresponding item in the array.

  3. Add a select all checkbox to the template and bind its state to a boolean variable.

  4. Use to watchmonitor 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 selectAllvariable to represent the state of the check box, and an itemsarray to store the state of all items that need to be selected. In the template, use v-forthe 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 selectAllthe variable.

In watch, monitor selectAllthe change of the variable, when its state changes, traverse itemseach item in the array, and set its state to the selectAllstate of to realize the all-selection function.

The result display:

insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/weixin_46098577/article/details/131221719