Files
lingji-work-fe/src/components/common-select/index.vue
2025-09-15 19:40:07 +08:00

128 lines
3.1 KiB
Vue

<!--
* @Author: RenXiaoDong
* @Date: 2025-06-25 14:02:40
-->
<template>
<Select
v-model:value="selectedValues"
:mode="multiple ? 'multiple' : undefined"
size="middle"
:placeholder="placeholder"
:allowClear="allClear"
:showSearch="allowSearch"
showArrow
:maxTagCount="maxTagCount !== undefined ? maxTagCount : (multiple ? 3 : undefined)"
@change="handleChange"
:filterOption="allowSearch ? filterOption : undefined"
>
<Option v-for="(item, index) in validOptions" :key="index" :value="item.value" :label="item.label">
<div class="flex items-center">
<img v-if="item.icon" :src="item.icon" class="w-16px h-16px mr-4px rounded-4px" />
<span>{{ item.label }}</span>
</div>
</Option>
<template #tag="{ label, icon }">
<div class="flex items-center">
<img v-if="icon" :src="icon" class="w-16px h-16px mr-4px rounded-4px" />
<span>{{ label }}</span>
</div>
</template>
<template v-if="!allowSearch" #empty>
<div v-if="validOptions.length === 0" class="empty-placeholder">
{{ placeholder || '暂无数据' }}
</div>
</template>
</Select>
</template>
<script setup>
import { Select } from 'ant-design-vue';
const { Option } = Select;
import { ref, watch, computed } from 'vue';
const props = defineProps({
modelValue: {
type: [Array, String, Number],
default: () => [],
},
multiple: {
type: Boolean,
default: true,
},
placeholder: {
type: String,
default: '全部',
},
options: {
type: Array,
default: () => [],
},
maxTagCount: {
type: Number,
default: undefined,
},
allClear: {
type: Boolean,
default: true,
},
allowSearch: {
type: Boolean,
default: false,
},
});
const emits = defineEmits(['update:modelValue', 'change']);
const selectedValues = ref(props.multiple ? [] : '');
// 计算有效选项,兼容不同的数据格式
const validOptions = computed(() => {
if (!props.options || !Array.isArray(props.options)) {
return [];
}
return props.options
.filter(item => item && (item.id !== undefined || item.value !== undefined) && (item.name !== undefined || item.label !== undefined))
.map(item => ({
...item,
value: item.id !== undefined ? item.id : item.value,
label: item.name !== undefined ? item.name : item.label
}));
});
watch(
() => props.modelValue,
(newVal) => {
selectedValues.value = newVal;
},
{ immediate: true },
);
watch(selectedValues, (newVal) => {
emits('update:modelValue', newVal);
});
const handleChange = (value) => {
selectedValues.value = value;
emits('change', value);
};
// 搜索过滤函数
const filterOption = (input, option) => {
// 确保 input 和 option.label 都存在且为字符串
if (!input || !option || !option.label) {
return false;
}
// 不区分大小写的模糊搜索
return option.label.toString().toLowerCase().includes(input.toLowerCase());
};
</script>
<style scoped>
.empty-placeholder {
padding: 8px 12px;
color: #8f959e;
text-align: center;
}
</style>