Vue封装Vant选择器组件

由于Vant原生的选择器组件只支持值列表的数据,而不支持键值对列表的数据,并且使用较为麻烦,于是对Vant的选择器组件进行了封装。

  • 封装组件代码
     
    <template>
      <!-- 封装vant的选择器 -->
      <div>
        <van-field
          readonly
          clickable
          name="picker"
          :value="text"
          :label="label"
          :placeholder="placeholder"
          @click="showPicker = true"
        />
        <van-popup v-model="showPicker" position="bottom">
          <van-picker
            show-toolbar
            :columns="columns"
            @confirm="onConfirm"
            @cancel="showPicker = false"
          />
        </van-popup>
      </div>
    </template>
    <script>
    export default {
      props: {
        data: {
          default: null,
          type: Array
        },
        value: {
          default: "",
          type: String
        },
        label: {
          default: "选择器",
          type: String
        },
        placeholder: {
          default: "点击选择",
          type: String
        }
      },
      computed: {
        columns() {
          let values = this.data.map(item => {
            return item.value;
          });
          return values;
        }
      },
      data() {
        return {
          showPicker: false,
          text: ""
        };
      },
      methods: {
        onConfirm(value, index) {
          let key = this.data[index].key;
          this.text = value;
          this.$emit("input", key);
          this.showPicker = false;
        }
      }
    };
    </script>

  • 使用方法
    <template>
      <div>
        <my-vant-pcker
          v-model="value"
          :data="data"
          label="城市选择"
          placeholder="请选择城市"
        ></my-vant-pcker>
      </div>
    </template>
    <script>
    import MyVantPcker from "@/components/MyVantPcker";
    export default {
      components: { MyVantPcker },
      data() {
        return {
          value: "",
          data: [
            {
              key: "hangzhou",
              value: "杭州"
            },
            {
              key: "shanghai",
              value: "上海"
            },
            {
              key: "beijing",
              value: "北京"
            }
          ]
        };
      }
    };
    </script>