首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何正确地选中所有复选框并使用Vue更改状态?

如何正确地选中所有复选框并使用Vue更改状态?
EN

Stack Overflow用户
提问于 2019-12-14 16:30:16
回答 1查看 1.1K关注 0票数 0

搜索此问题已有一段时间了,现在我要选择所有复选框:

1.-当选中标记为"Seleccionar Todos“的复选框时,必须选中所有当前复选框。

2.-如果选中复选框"Seleccionar todos",但用户取消选中"Seleccionar todos“旁边的任何复选框,则必须禁用select all checkbx。

Tickets.vue (这个文件创建了我需要的表,这里是我需要帮助的地方)

代码语言:javascript
复制
<template>
  <v-card class="elevation-5 pa-3">
    <div>
    <v-checkbox color="primary" @change="selectall()" :id="`todos`" :label="`Seleccionar Todo`" :checked="booleanValue" :val="'FALSE'" ref="todos"/>
    </div>
    <v-data-table
        ref="data_table"
        :headers="configuracion.configClientes.encabezados"
        expand
        rows-per-page-text="Filas por página"
        :rows-per-page-items="[10, 20, 55, { text: 'Todas', value: -1 }]"
        :no-results-text="'No se han encontrado tickets'"
        :item-key="configuracion.configClientes.itemKey"
        v-model="seleccion"
        :configuracion="configuracion.configClientes"
        :items="cat_clientes.catalogo"
    >
      <template slot="headerCell" slot-scope="props">
          <span>
            {{ props.header.text }}
          </span>
      </template>

      <template slot="items" slot-scope="props">
        <tr>
          <td
              v-for="columna in configuracion.configClientes.encabezados"
              v-if="columna.value !== '$acciones'"
              :key="keyUUID()"
          >
            {{ formatearColumna( props.item, columna ) }}

          </td>
          <td> 
            <v-checkbox :val="items.FOLIO" v-model="props.items" color="primary" @change="changeCheckbox(props.item.FOLIO)"/>
            </td>
        </tr>
      </template>

      <template slot="no-data">
        <v-alert :value="true" color="warning" icon="warning">
          {{ configuracion.mensajeVacia ? configuracion.mensajeVacia : 'No hay tickets' }}
        </v-alert>
      </template>
    </v-data-table>
  </v-card>
</template>

<script>
  import { mapActions, mapGetters } from 'vuex';
  /* mixins */
  import { mixins_generales } from "../Mixins/generales";
  import { formatos } from "../Mixins/formatos";

  export default {
    mixins: [mixins_generales, formatos],

    props: {
      configuracion: {
        type: Object,
        default: () => {
          return {
        configClientes: {
          seleccionable: true,
          itemKey: 'id',
          editable: true,
          eliminable: true,
          buscable: true,
          expandible: true,
          labelBusqueda: 'Buscar ticket',
          mensajeVacia: 'No hay tickets',
          encabezados: [
            {text: 'Folio', value: 'FOLIO', align: 'left'},
            {text: 'Fecha', value: 'FECHA', align: 'left'},
            {text: 'Hora', value: 'HORA', align: 'left'},
            {text: 'Sub-Total', value: 'SUBTOTAL', align: 'left'},
            {text: 'IVA', value: 'IVA', align: 'left'},
            {text: 'Total', value: 'TOTAL', align: 'left'},
            {text: 'Procesar', value: '$acciones', align: 'left'}
          ]
        },
        clienteSeleccionado: null,
      };
        }
      },
      items: {
        type: Array,
        default: () => []
      }
    },

    data() {

      return {
          checked:false,
        seleccion: [],
        todos:[],
        booleanValue:false
      };
    },
    computed: {
      ...mapGetters([
        'cat_clientes'
      ]),
    },
    methods: {
              ...mapActions([
        'LLENAR_CAT_CLIENTES',
        'AGREGAR_CAT_CLIENTE',
        'QUITAR_CAT_CLIENTE',
        'MARCAR_CAT_CLIENTES_CONSULTADO'
      ]),
          handleInput(e) {
      console.log("handleInput in App :: ", e);
      this.formattedValue = e;
    },
      onClick(props) {
        if (this.configuracion.expandible) {
          props.expanded = !props.expanded;
        }
      },

      onEditar(item) {
        this.$emit('editar', item);
      },

      onEliminar(item) {
        this.$emit("eliminar", item);
      },

      formatearColumna(item, encabezado) {
        if (item[encabezado.value]) {
          if (encabezado.formato) {
            if (encabezado.formato === 'moneda') {
              return this.formatearMoneda(item[encabezado.value]);
            }
          }

          return item[encabezado.value];
        }
        return 'N/A';
      },

      override_genPagination() {
        const that = this.$refs.data_table;
        that.genPagination = () => {
          let pagination = '–';

          if (that.itemsLength) {
            const stop = that.itemsLength < that.pageStop || that.pageStop < 0
              ? that.itemsLength
              : that.pageStop;

            pagination = that.$scopedSlots.pageText
              ? that.$scopedSlots.pageText({
                pageStart: that.pageStart + 1,
                pageStop: stop,
                itemsLength: that.itemsLength
              })
              : `${that.pageStart + 1}-${stop} de ${that.itemsLength}`;
          }

          return that.$createElement('div', {
            'class': 'datatable__actions__pagination'
          }, [pagination]);
        }
      },
            cargar() {
        this.MOSTRAR_LOADING('Obteniendo tickets');
        const url = this.g_url + '/php/catalogos/obtenertickets.php';

        this.$http.get(url)
          .then(response => {
            const respuesta = response.data;
            console.log('[Tickets](cargar)', response);

            if (!this.RespuestaSinErrores(respuesta, 'Ha ocurrido un error en el servidor al obtener los tickets')) {
              return;
            }

            // actualizar el state con el catálogo y mostrar al usuario
            this.MOSTRAR_SNACKBAR({texto: 'Tickets cargados', color: 'success', arriba: true, derecha: true});
            this.LLENAR_CAT_CLIENTES(respuesta.conceptos.catalogo);
            this.todos = respuesta.todos;
            this.MARCAR_CAT_CLIENTES_CONSULTADO();
          }, error => {
            this.MostrarErrorConexion(error);
          });
      },
 changeCheckbox(item)
 {
   let aux = 0;
   this.booleanValue = false;

   if(this.seleccion.length == 0)
   {
     //Array Vacio
     this.seleccion.push(item);
   }else{
     for(var i=0;i < this.seleccion.length;i++)
     {
       if(this.seleccion[i] == item)
       {
         //Existe en array
         this.seleccion.splice(this.seleccion.indexOf(item), 1);
         aux = 1;
         break;
       }
     }
     if(aux==0)
     {
       this.seleccion.push(item);
     }
   }
   console.log(this.seleccion);
 },
 toggleAll() {
  this.items.forEach((props, items) => {
    this.$set(this.props.items, "value", !this.selectDeselectAll);
  });
},
 toFol()
 {
   let istodos = document.getElementById("todos").checked;
   let fol = "";
   if(this.seleccion.length == 0 && istodos == false)
    {
      this.MOSTRAR_SNACKBAR({texto: 'No ha elegido tickets para facturar', color: 'error'});
      return false;
    }

    if(istodos == true)
    {
      return this.todos;
    }else{
      return this.seleccion;
    }
 }
    },//Fin metodos

    mounted() {
      this.override_genPagination();
    },
          created() {
      if (!this.cat_clientes.consultado) {
        this.cargar();
      }
    },
    watch: {
      seleccion(valor) {
        this.$emit('seleccion', valor);
      }
    }
  }
</script>

我以这个url https://makitweb.com/check-uncheck-all-checkboxes-with-vue-js/ & @Robin ZecKa法拉利的答案为例(因为他的例子与我的代码需要完全不同,但这是一个帮助)。

编辑:当前的方法使用罗宾ZecKa法拉利答案,但它只是勾选待办事项,而不是所有复选框。

EN

回答 1

Stack Overflow用户

发布于 2019-12-14 17:03:18

请下次尝试与我们分享一个较小的代码,尝试隔离您的问题。

在这里,我使用watch方法来触发一个函数,每次选择/取消选择所有按钮上的值发生变化。

还请看一下this.$set,使用它来保持数据的反应性是很重要的。不要像this.options[index].value = newValue那样直接修改数据。关于深度反应性的更多信息:https://v2.vuejs.org/v2/guide/reactivity.html

在CodeSandBox:https://codesandbox.io/s/checkdeselect-all-bu0p4上查看它

代码语言:javascript
复制
<template>
  <div class="hello">
    <input type="checkbox" v-model="selectDeselectAll">Select/deselect All
    <ul>
      <li v-for="(option, index) in options" :key="'option'+index">
        <input type="checkbox" v-model="options[index].value">
        {{option.label}}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      selectDeselectAll: false,
      options: [
        { label: "option 1", value: false },
        { label: "option 2", value: false },
        { label: "option 3", value: false }
      ]
    };
  },
  watch: {
    selectDeselectAll: function(newValue) {
      this.options.forEach((option, index) =>
        // it's important to use $set to allow Reactivity in Depth
        // See: https://v2.vuejs.org/v2/guide/reactivity.html
        this.$set(this.options[index], "value", newValue)
      );
    }
  }
};
</script>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59337026

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档