antdesign 使用a-select实现特殊select

136 阅读1分钟

展开前

image.png

展开后 image.png

<template>
  <div
    :class="{ 'select-name-collaped': hasCollaped }"
    class="select-name"
    @click="handleCollaped"
  >
    {{ currentSelectName }}
    <caret-down-outlined
      class="ant-select-suffix"
      :class="{ rotate: !hasCollaped }"
    />
  </div>
  <a-select
    ref="selectRef"
    class="select"
    :class="{ 'select-show': !hasCollaped }"
    dropdownClassName="select-dropdown"
    v-if="!hasCollaped"
    show-search
    style="width: 360px"
    :defaultOpen="!hasCollaped"
    :options="dataList"
    :field-names="{ label: 'title', value: 'id' }"
    :filter-option="filterOption"
    @change="handleChange"
    @dropdownVisibleChange="handleBlurSelect"
    placeholder="请选择"
  />
</template>

<script lang="ts" setup>
import { ref, Ref, watch } from "vue";
import { currentSelectValue, currentSelectName } from "../../store";
import useFetchList from "@/utils/tools/useFetchList";

const { dataListData } = useFetchSiteList(); //useFetchSiteList 为取选项数据的工具函数
const hasCollaped: Ref<boolean> = ref(true);
const selectRef = ref();

//选择框更改选择
const handleChange = (id: number, option: any) => {
  currentSelectName.value = option.title;
  currentSelectValue.value = id;
  hasCollaped.value = true;
};

//控制三角形的collapse
const handleCollaped = () => {
  hasCollaped.value = !hasCollaped.value;
};

// 让选择框隐藏
const handleBlurSelect = () => {
  hasCollaped.value = true;
};

// 筛选控制
const filterOption = (input: string, option: any) => {
  return option.title.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

//提供给外部使用
defineExpose({
  dataListData,  
});

//当打开选择框时,让选择框处于focus
watch(hasCollaped, (val) => {
  if (val) {
    selectRef.value.focus();
  }
});
</script>
<style lang="scss">
.rotate {
    transform: rotate(180deg);
    color: #0052e2;
}
</style>