【问题标题】:How to create a checkbox with value with Vue如何使用 Vue 创建一个带值的复选框
【发布时间】:2024-05-16 10:45:02
【问题描述】:

我正在尝试使用 php 文件中的数据创建一个表,但我找不到一种方法来创建一个值为 FOLIO 和 id 的复选框,这是我的方法:

Tickets.vue

    <template>
    <v-card class="elevation-5 pa-3">

    <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>
        </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: 'CHECK', align: 'center'}
          ]
        },
        clienteSeleccionado: null,
      };
        }
      },
      items: {
        type: Array,
        default: () => []
      }
    },

    data() {

      return {
          checked:false,
        seleccion: [],
        busqueda: ''
      };
    },
    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.MARCAR_CAT_CLIENTES_CONSULTADO();
          }, error => {
            this.MostrarErrorConexion(error);
          });
      },

    },

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

obtenertickets.php

<?php
require_once '../lib/includes/generales.php';
g_Includes();

session_start();

/* funciones */
require_once '../lib/funciones/generales.php';
require_once '../lib/funciones/mysql.php';

try {

  $respuesta = array();
  $conexion = ConexionUsuario($_SESSION['factura_libre']['id']);
  $fechainicial = date("Y-m-01");
  $fechafinal = date("Y-m-d");
  $tickets = array();

    $query = "SELECT * FROM facturas WHERE EDO = 3 AND FECHA BETWEEN '$fechainicial' AND '$fechafinal'
    AND FOLIO NOT IN (SELECT folio FROM fw_tickets_facturados)
     ORDER BY folio";
    $total = 0;
    $id = 1;
    foreach ($conexion->query($query) as $row) {
      $concepto = array(
        "id" => $id,
        "FOLIO" => intval($row['FOLIO']),
        "FECHA" => $row['FECHA'],
        "HORA" => $row['HORA'],
        "SUBTOTAL" => $row['SUBTOTAL'],
        "IVA" => $row['IVA'],
        "TOTAL" => $row['TOTAL'],
        "DESCUENTO" => $row['DESCUENTO'],
        "CHECK" => "<input type='checkbox' value='$row[FOLIO]' id='c$row[FOLIO]'/>"
      );
      $total += $row["TOTAL"];
      $tickets[] = $concepto;
      $id++;
    }

    $respuesta['conceptos']['catalogo'] = $tickets;
    $respuesta['total'] = $total;

  EnviarRespuesta(false, $respuesta);
} catch (PDOException $err) {
  global $logger;
  $logger->RegistrarError("{$err->getFile()}[{$err->getLine()}]:\r\n{$err->getMessage()}", 'sql');
  EnviarRespuesta(true, array("error" => "(P.Err.) No ha sido posible obtener los tickets."));
} catch (Exception $err) {
  EnviarRespuesta(true, array("error" => $err->getMessage()));
}

所以我可以运行一个函数来读取所有选中的复选框并继续,已经搜索了 3 天没有运气和很多错误 x_x 提前谢谢你。 干杯~

【问题讨论】:

    标签: php html vue.js


    【解决方案1】:

    您可能正在&lt;v-checkbox&gt; vuetify 组件中寻找true-valuefalse-value。它可能看起来像这样。

    <v-data-table
                :items="cat_clientes.catalog"
                :headers="this.headers"
                hide-default-headers
                :items-per-page="10"
                :search="search"
        >
            <template v-slot:item.status="{ item }">
                <v-checkbox true-value="Done" false-value="Open" v-model="itemStatus" @change="changeCheckbox(item)"
                            color="primary"/>
            </template>
    

    【讨论】:

    • 差不多了,有什么建议可以将 Done/Open 值更改为实际 FOLIO?
    最近更新 更多