原
vue3封装一个通用的数据字典选择。支持v-model双向帮定值,支持change事件,支持传递提示语placeholder

代码如下:
<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>
欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739。有需要软件开发,或者学习软件技术的朋友可以和我联系~(Q:815170684)
评价
排名
8
文章
221
粉丝
7
评论
7
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:
50010702506256


欢迎加群交流技术