tnblog
首页
视频
资源
登录

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

81人阅读 2025/3/27 20:00 总访问:823869 评论:0 收藏:0 手机
分类: 前端

代码如下:

  1. <template>
  2. <el-select
  3. v-model="innerValue"
  4. @change="handleSelectChange"
  5. class="select-dic"
  6. size="default"
  7. :placeholder="placeholder"
  8. clearable
  9. >
  10. <el-option
  11. v-for="item in dicDatas"
  12. :key="item.dictValue"
  13. :value="item.dictValue"
  14. :label="item.dictLabel"
  15. />
  16. </el-select>
  17. </template>
  18. <script setup lang="ts">
  19. import { ref, watch, onMounted } from 'vue';
  20. // import type { PropType } from 'vue';
  21. import request from '/@/utils/requestTools';
  22. // 定义组件props类型
  23. interface DictDataItem {
  24. dictValue: string;
  25. dictLabel: string;
  26. }
  27. const props = defineProps({
  28. modelValue: {
  29. type: String,
  30. default: ''
  31. },
  32. dictType: {
  33. type: String,
  34. required: true
  35. },
  36. placeholder: {
  37. type: String,
  38. default: '请选择类型'
  39. }
  40. });
  41. const emit = defineEmits<{
  42. (e: 'update:modelValue', value: string): void;
  43. (e: 'change', value: string): void;
  44. }>();
  45. // 响应式状态
  46. const innerValue = ref(props.modelValue);
  47. const dicDatas = ref<DictDataItem[]>([]);
  48. // 初始化加载字典数据
  49. const loadDictData = async () => {
  50. try {
  51. const res:any = await request.get('/watertap/api/SysDictData/getSysDictDataByType', {
  52. dictType: props.dictType
  53. });
  54. dicDatas.value = res.data || [];
  55. } catch (error) {
  56. console.error('加载字典数据失败:', error);
  57. // 这里可以添加错误处理逻辑
  58. }
  59. };
  60. // 处理选择变化
  61. const handleSelectChange = (value: string) => {
  62. emit('update:modelValue', value);
  63. emit('change', value);
  64. };
  65. // 监听外部modelValue变化
  66. watch(
  67. () => props.modelValue,
  68. (newVal) => {
  69. innerValue.value = newVal;
  70. }
  71. );
  72. // 生命周期钩子
  73. onMounted(loadDictData);
  74. </script>
  75. <style scoped lang="scss">
  76. .select-dic {
  77. width: 100%;
  78. :deep(.el-input__inner) {
  79. padding: 0 15px;
  80. }
  81. }
  82. </style>

欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739。有需要软件开发,或者学习软件技术的朋友可以和我联系~(Q:815170684)

评价
这一生多幸运赶上过你.
排名
8
文章
221
粉丝
7
评论
7
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术