el-select 的组件示例

138 阅读1分钟

以下是一个封装了 el-select 的组件示例,它支持单选与多选、远程搜索并具有默认值的功能:

<template> <el-select v-model="currentValue" filterable remote :remote-method="searchMethod" :multiple="isMultiple" :collapse-tags="collapseTags" :max-tag-count="maxTagCount" :multiple-limit="multipleLimit" :loading="isLoading" :placeholder="placeholder" :disabled="disabled" > <el-option v-for="(option, index) in options" :key="option.value" :label="option.label" :value="option.value" /> </el-select> </template> < script >
  export default {
    name: 'MySelect',
    props: {
      value: {
        type: [String, Number, Array],
        default: '',
      },
      multiple: {
        type: Boolean,
        default: false,
      },
      collapseTags: {
        type: Boolean,
        default: false,
      },
      maxTagCount: Number,
      multipleLimit: Number,
      searchMethod: Function,
      placeholder: String,
      disabled: Boolean,
    },
    data() {
      return {
        currentValue: this.multiple ? (Array.isArray(this.value) ? this.value : []) : this.value,
        isLoading: false,
        options: [],
      }
    },
    watch: {
      value(newValue) {
        this.currentValue = newValue;
      },
      currentValue(newValue) {
        this.$emit('input', newValue);
      },
    },
    computed: {
      isMultiple() {
        return !!this.multiple;
      },
    },
    methods: {
      async searchMethod(queryString) {
        if (!queryString) return;
        this.isLoading = true;
        const res = await this.searchMethod(queryString);
        if (res.code === 0 && Array.isArray(res.data)) {
          this.options = res.data.map(item => ({
            label: item.label,
            value: item.value,
          }));
        } else {
          this.options = [];
        }
        this.isLoading = false;
      },
    },
    created() {
      if (this.isMultiple && !Array.isArray(this.currentValue)) {
        console.warn(`MySelect: in multiple mode, the v-model value must be an array`);
      }
    },
  }; < /script> <style scoped> / * 自定义样式 * / </style >

上述代码中,我们使用了以下的输入参数:

  • value:当前选中的值,可以是单个值也可以是值的数组。
  • multiple:是否为多选模式,默认为单选模式。
  • collapseTags:是否将多选结果可视化展示在选项下方,仅在 multiple 为 true 时生效,默认为 false,不展示。
  • maxTagCount:当开启 collapse-tags 时,多选数量超过该值时会以 $x 几种的形式展示。默认值为 -1,即不限制展示数量。
  • multipleLimit:当控件在多选状态下时,用户最多可以选择的项目数,其中 0 表示不限制。默认值为 0。
  • searchMethod:一个远程搜索的函数,接收当前输入框中的搜索字符串作为参数,并返回一个 Promise 对象,resolve 后应该包含 {code: number, data: []} 的数据,其中 data 是一个待选择的选项数组,即可通过 setValue 方法设置的 values 数组。
  • placeholder:当没有选中值时的提示文本。
  • disabled:是否禁用。

其他参数与 el-select 提供的参数一致,包括:

  • loading:控件是否正在加载。
  • option:下拉列表中客户端渲染的选项数组。
  • remote-method:远程搜索使用的函数。
  • filterable:搜索框是否可见。

本示例在 created 钩子函数中根据参数检查了是否为单选或多选模式,并在多选模式下强行将 value 转换成数组,防止出现由于指定多选但传入的是单个值而造成的错误。