vue3封装一个通用的数据字典选择。支持v-model双向帮定值,支持change事件,支持传递提示语placeholder 电脑版发表于:2025/3/27 20:00 代码如下: ``` <template> <el-select v-model="innerValue" @change="handleSelectChange" class="select-dic" size="default" :placeholder="placeholder" clearable > <el-option v-for="item in dicDatas" :key="item.dictValue" :value="item.dictValue" :label="item.dictLabel" /> </el-select> </template> <script setup lang="ts"> import { ref, watch, onMounted } from 'vue'; // import type { PropType } from 'vue'; import request from '/@/utils/requestTools'; // 定义组件props类型 interface DictDataItem { dictValue: string; dictLabel: string; } const props = defineProps({ modelValue: { type: String, default: '' }, dictType: { type: String, required: true }, placeholder: { type: String, default: '请选择类型' } }); const emit = defineEmits<{ (e: 'update:modelValue', value: string): void; (e: 'change', value: string): void; }>(); // 响应式状态 const innerValue = ref(props.modelValue); const dicDatas = ref<DictDataItem[]>([]); // 初始化加载字典数据 const loadDictData = async () => { try { const res:any = await request.get('/watertap/api/SysDictData/getSysDictDataByType', { dictType: props.dictType }); dicDatas.value = res.data || []; } catch (error) { console.error('加载字典数据失败:', error); // 这里可以添加错误处理逻辑 } }; // 处理选择变化 const handleSelectChange = (value: string) => { emit('update:modelValue', value); emit('change', value); }; // 监听外部modelValue变化 watch( () => props.modelValue, (newVal) => { innerValue.value = newVal; } ); // 生命周期钩子 onMounted(loadDictData); </script> <style scoped lang="scss"> .select-dic { width: 100%; :deep(.el-input__inner) { padding: 0 15px; } } </style> ```