从零实现Vue的组件库(十)- Select 实现

当选项过多时,使用下拉菜单展示并选择内容。

Select 组件主要特点在于:
  • 数据双向绑定,下拉列表变动时,选中项如何回显;
  • 单选、多选的区分,以及对应处理。

1. 实例

代码

<fat-select v-model="inputValue">
    <fat-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value"
    >{{ item.label }}</fat-option>
</fat-select>
复制代码

实例地址:Select 实例

代码地址:Github UI-Library

2. 原理

Select 组件的基本结构如下

主要可分为两个部分:

  • 显示框:用来展示已经选中项,包含取消按钮;
  • 下拉框:包含已选中的高亮项,禁用项,默认选择选项等,具备点击选中,再次点击取消的操作。

fat-select 显示框

<template>
    <div
      :class="['select-wrapper', { 'is-disabled': disabled }]"
      tabindex="0"
      @click.stop="isOpen = !disabled && !isOpen"
      @blur="handleBlur"
    >
      <div class="select-top-part">
        <template v-if="!selectItems.length">
          <span class="placeholder">{{ placeholder }}</span>
        </template>

        <template v-else>
          <div>{{ selectItems[0].label }}</div>
        </template>
      </div>
      <!-- 下拉框 -->
      <div class="select-bottom-part" v-show="isOpen">
        <slot></slot>
      </div>
    </div>
</template>

<script>
export default {
  props: {
    placeholder: { type: String, default: "请选择" },
    optionKey: { type: String, default: "value" },
    value: { type: [String, Object, Number, Array] }
  },
  model: {
    prop: "value",
    event: "input"
  },
  data() {
    return {
      isOpen: false,

      selectValue: [],

      selectItems: []
    };
  },
  provide() {
    return {
      fatSelect: this
    };
  },
  watch: {
    value: {
      handler(value) {
        const { multiple } = this;
        const init = value ? value : multiple ? [] : "";
        this.selectValue = multiple ? [...init] : init;
      },
      immediate: true
    },
    selectValue: {
      handler(value) {
        this.selectItems = [];
      }
    }
  },
  methods: {
    handleDelete(item) {
      const { value } = item;
      this.selectValue = this.selectValue.filter(item => item !== value);
      this.$emit("input", this.selectValue);
      this.$emit("change", this.selectValue);
    },
    handleBlur(event) {
      this.isOpen = false;
      this.$emit('blur', event);
    }
    ...
  }
};
</script>
复制代码

利用 tabIndex 属性使得最外层的 div 能够触发 blur 事件,如果失焦就收起下拉框。

<div
    :class="['select-wrapper', { 'is-disabled': disabled }]"
    tabindex="0"
    @click.stop="isOpen = !disabled && !isOpen"
    @blur="handleBlur"
>
    ...
    <!-- 下拉框 -->
    <div class="select-bottom-part" v-show="isOpen">
        <slot></slot>
    </div>
</div>

handleBlur(event) {
    this.isOpen = false;
    this.$emit('blur', event);
}
复制代码

组件实现数据双向绑定,当 v-model 对应的值变动时,Select 组件的值也会发生改变,但是显示框内所呈现的是选中项的 label 属性,所以将选中值 selectValue 和选中项 selectItems 进行区分。

同时配置 v-model 相关属性,同时监测 watch 相关 value 具体如下

model: {
    prop: "value",
    event: "input"
},
watch: {
    value: {
        handler(value) {
            const { multiple } = this;
            const init = value ? value : multiple ? [] : "";
            this.selectValue = multiple ? [...init] : init;
        },
        immediate: true
    }
}
复制代码

同时利用 provide 向其所有下拉框注入一个依赖,用于访问 selectValueselectItemspropdata

provide() {
    return {
        fatSelect: this
    };
}
复制代码

默认 optionKey: { type: String, default: "value" } 作为下拉项的唯一标识,默认值为 value ,也可自定义。

fat-option 下拉框

利用插槽将下拉框插入 Select 组件中,其具体定义如下

<template>
  <div
    :class="['select-option-wrapper', { 'is-selected': isSelect }, { 'is-disabled': disabled }]"
    @click.stop="handleClick"
  >
    <slot></slot>
  </div>
</template>
<script>
export default {
  props: {
    value: { type: [Object, String, Number], required: true },
    label: { type: String },
    disabled: { type: Boolean, defa: false }
  },
  inject: ["fatSelect"],
  computed: {
    isSelect() {
      const {
        fatSelect: { optionKey, selectItems }
      } = this;
      const key = this[optionKey] || this.$attrs[optionKey];

      return selectItems.find(item => item.key === key);
    }
  },
  watch: {
    ["fatSelect.selectValue"]: {
      handler(newValue) {
        const {
          value,
          label,
          fatSelect: { optionKey, multiple, selectValue }
        } = this;
        const key = this[optionKey] || this.$attrs[optionKey];

        if (
          newValue === value ||
          (Array.isArray(newValue) && newValue.find(item => item === value))
        ) {
          if (!multiple) {
            this.fatSelect.selectItems = [
              {
                key,
                label,
                value
              }
            ];
          } else {
            this.fatSelect.selectItems.push({
              key,
              label,
              value
            });
          }
        }
      },
      immediate: true
    }
  },
  methods: {
    ...
  }
};
</script>
复制代码

利用 inject: ["fatSelect"] 将上述 provideSelect 组件注入到当前选项中,

通过 this.fatSelect 来访问父组件的 selectItems 来判断,当前选项是否为选中项。

isSelect() {
    const {
        fatSelect: { optionKey, selectItems }
    } = this;
    const key = this[optionKey] || this.$attrs[optionKey];

    return selectItems.find(item => item.key === key);
}
复制代码

同时watch fatSelect.selectValue 也就是选中值,之前说过该组件实现数据的双向绑定,当Select组件 v-model 绑定的值变动时,需要同步到下拉项。

["fatSelect.selectValue"]: {
    handler(newValue) {
        const {
          value,
          label,
          fatSelect: { optionKey, multiple, selectValue }
        } = this;
        const key = this[optionKey] || this.$attrs[optionKey];

        if (
          newValue === value ||
          (Array.isArray(newValue) && newValue.find(item => item === value))
        ) {
          if (!multiple) {
            this.fatSelect.selectItems = [
              {
                key,
                label,
                value
              }
            ];
        } else {
            this.fatSelect.selectItems.push({
              key,
              label,
              value
            });
          }
        }
    },
    immediate: true
}
复制代码

如果对应的 fatSelect.selectValue 变动时,要判断当前选项的 optionKey 是否在 selectValue 中,如果存在,就将

this.fatSelect.selectItems = [
    {
        key,
        label,
        value
    }
];
复制代码
3. 结论

忽略了 Select 组件的一些细节,例如多选、单选的逻辑,重点展示了下该组件的设计逻辑,以及数据绑定的实现方式,总结了一些实际业务中碰到的问题。

往期文章:

原创声明: 该文章为原创文章,转载请注明出处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue组件<el-select-tree>是一个结合了ElementUI的el-select和el-tree的下拉树型选择组件。通过这个组件,可以实现选择任意一个父集的子集,并获取当前子集的父级并进行保存操作。 在使用情景中,可以将下拉树看作是树与下拉框的结合版,但是树的点击事件在下拉树中并不适用。解决这个问题的办法是通过下拉树组件自带方法@confirm来完成。在使用@confirm方法之前,需要将需要的数据传入,否则点击事件不会获取任何数据。然后在方法中进行匹配循环,找出子集对应的父级并一起存入数组中。 需要注意的是,在面临编辑操作的情景中,如果将下拉树的数据传回来默认展示在下拉框中,传回来的数据包含一个父级,可能会导致此父级元素全被默认选择。因此,在处理数据时,需要将父级排除以避免这个问题的发生。 总结起来,使用<el-select-tree>组件可以实现下拉树型选择,并获取选择子集的父级进行保存操作。虽然这个方法看起来繁琐,但目前还没有更好的办法来处理这个问题。<span class="em">1</span><span class="em">2</span> #### 引用[.reference_title] - *1* [el-select-tree:ElementUI的el-select与el-tree结合](https://download.csdn.net/download/weixin_42135773/18435535)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [vue组件<el-select-tree>的使用](https://blog.csdn.net/weixin_44519803/article/details/119748522)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值