[Experiencia práctica] El paquete selector de selector en vant facilita la selección de formularios

prefacio

Para el componente selector, el componente selector en vant es una opción muy adecuada. No solo proporciona opciones de configuración flexibles, sino que también se puede combinar fácilmente con otros componentes vant para ayudarnos a crear rápidamente páginas móviles hermosas y fáciles de usar. En este artículo, presentaré cómo realizar un empaque secundario basado en el componente de selección de vant para satisfacer mejor las necesidades comerciales reales.


Ideas de implementación

  1. Primero defina una página de subcomponente para encapsular el selector;
  2. Introduzca y registre el componente de encapsulación (subcomponente) en el componente principal (la página utilizada) y luego utilícelo en la página En el componente principal, vincule múltiples atributos a la etiqueta (nombre del componente registrado), y el atributo debe ser pasado a montaje El valor de se recibe al recibir datos propsen el subcomponente (archivo de encapsulación);
  3. Personalice el evento determinado en el componente secundario. Después de llamar a este evento, el componente secundario this.$emit('自定义事件名',要传递的数据)envía los datos que el componente principal puede escuchar y, finalmente, el componente principal escucha el evento del componente secundario, llama al evento y recibe los datos pasados.

parámetros definidos

parámetro describir
selecciona valor valor de enlacemodel
valor clave keycampo enlazado
etiqueta clave valuecampo enlazado
columnas La fuente optionde datos
requerido Ya sea para mostrar *el cheque
normas Reglas de validación
requerido ¿Es obligatorio?
confirmar La función de devolución de llamada seleccionada

archivo de paquete

<template>
  <div>
    <van-field v-model="textValue" v-bind="$attrs" :name="$attrs.name" :rules="rules" :required="required" :readonly="readonly"
      :is-link="islink" @click="show = !show" />
    <van-popup v-model="show" get-container="body" position="bottom">
      <van-picker :columns="columns" show-toolbar :value-key="keyValue" :title="$attrs.label" @cancel="show = !show" @confirm="onConfirm">
        <template #option="option">
          {
   
   { option[keyLabel] }}
        </template>
      </van-picker>
    </van-popup>
  </div>
</template>

<script>
export default {
      
      
  props: {
      
      
    required: {
      
      
      type: Boolean,
    },
    readonly: {
      
      
      type: Boolean,
    },
    islink: {
      
      
      type: Boolean,
    },
    columns: {
      
      
      type: Array,
    },
    rules: {
      
      
      type: Array,
    },
    selectValue: {
      
      
      type: String,
    },
    keyValue: {
      
      
      type: String,
    },
    keyLabel: {
      
      
      type: String,
    },
  },
  data() {
      
      
    return {
      
      
      show: false,
      textValue: "",
      selectOptions: [],
    };
  },
  methods: {
      
      
    onConfirm(obj) {
      
      
      this.textValue = obj.label;
      this.show = !this.show;
      this.$emit("confirm", obj);
    },
    formatterValue(value) {
      
      
      let str = "";
      if (!this.columns.length || !value.length) {
      
      
        str = "";
      } else {
      
      
        let oArr = this.columns.filter((item) => {
      
      
          return item[this.keyValue].toString() == value.toString();
        });
        str = oArr[0][this.keyLabel];
      }

      return str;
    },
    //根据key值格式化成picker需要的option格式
    formatColumnsByKey() {
      
      
      let arr = [];
      let value = this.keyValue ? this.keyValue : "value";
      let label = this.keyLabel ? this.keyLabel : "label";
      this.columns.map((item) => {
      
      
        arr.push({
      
      
          label: item[label],
          value: item[value],
        });
      });
      this.selectOptions = arr;
    },
  },
  watch: {
      
      
    columns: {
      
      
      handler(newValue) {
      
      
        this.textValue = this.formatterValue(
          this.selectValue ? this.selectValue : ""
        );
      },
      deep: true,
      immediate: true,
    },
    selectValue: {
      
      
      handler(newValue) {
      
      
        this.textValue = this.formatterValue(newValue ? newValue : "");
      },
      deep: true,
      immediate: true,
    },
  },
};
</script>

usar archivo

<template>
  <div>
    <van-form validate-first>
      <VanSelect name="qylx" label="企业类型" placeholder="请选择企业类型" :selectValue="qylx" :keyValue="`value`" :keyLabel="`label`" :required="true"
        :readonly="true" :columns="qylxOption" :rules="rules.qybh" @confirm="qylxConfirm" />
      <div class="btnBomBox">
        <van-button round size="small" block @click="submitOn" type="info">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import VanSelect from "@/components/vanSelect/index";
export default {
      
      
  components: {
      
      
    VanSelect,
  },
  data() {
      
      
    return {
      
      
      qylx: "",
      qylxOption: [
        {
      
       label: "自营企业", value: "1" },
        {
      
       label: "其他企业", value: "2" },
      ],
      rules: {
      
      
        qybh: [
          {
      
      
            required: true,
            message: "请选择企业类型",
          },
        ],
      },
    };
  },
  methods: {
      
      
    // 点击确定
    qylxConfirm(value) {
      
      
      this.qylx = value.value;
    },
    // 提交
    submitOn() {
      
      
      console.log(this.qylx);
    },
  },
};
</script>

<style scoped>
.btnBomBox {
      
      
  padding: 0px 16px;
  display: flex;
  justify-content: center;
}
</style>

lograr efecto

inserte la descripción de la imagen aquí

Supongo que te gusta

Origin blog.csdn.net/Shids_/article/details/131086409
Recomendado
Clasificación