index.vue 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <template>
  2. <div class="icon-box">
  3. <el-input
  4. ref="inputRef"
  5. v-model="valueIcon"
  6. v-bind="$attrs"
  7. :placeholder="placeholder"
  8. :clearable="clearable"
  9. @clear="clearIcon"
  10. @click="openDialog"
  11. >
  12. <template #append>
  13. <el-button :icon="customIcons[iconValue] || ''" />
  14. </template>
  15. </el-input>
  16. <el-dialog v-model="dialogVisible" :title="placeholder" top="10%" width="40%">
  17. <el-input v-model="inputValue" placeholder="搜索图标" size="large" :prefix-icon="Icons.Search" />
  18. <el-scrollbar v-if="Object.keys(iconsList).length">
  19. <div class="icon-list">
  20. <div v-for="item in iconsList" :key="item" class="icon-item" @click="selectIcon(item)">
  21. <component :is="item"></component>
  22. <span>{{ item.name }}</span>
  23. </div>
  24. </div>
  25. </el-scrollbar>
  26. <el-empty v-else description="未搜索到您要找的图标~" />
  27. </el-dialog>
  28. </div>
  29. </template>
  30. <script setup lang="ts" name="SelectIcon">
  31. import { ref, computed } from 'vue'
  32. import * as Icons from '@element-plus/icons-vue'
  33. interface SelectIconProps {
  34. iconValue: string
  35. title?: string
  36. clearable?: boolean
  37. placeholder?: string
  38. }
  39. const props = withDefaults(defineProps<SelectIconProps>(), {
  40. iconValue: '',
  41. title: '请选择图标',
  42. clearable: true,
  43. placeholder: '请选择图标'
  44. })
  45. // 重新接收一下,防止打包后 clearable 报错
  46. const valueIcon = ref(props.iconValue)
  47. // open Dialog
  48. const dialogVisible = ref(false)
  49. const openDialog = () => (dialogVisible.value = true)
  50. // 选择图标(触发更新父组件数据)
  51. const emit = defineEmits<{
  52. 'update:iconValue': [value: string]
  53. }>()
  54. const selectIcon = (item: any) => {
  55. dialogVisible.value = false
  56. valueIcon.value = item.name
  57. emit('update:iconValue', item.name)
  58. setTimeout(() => inputRef.value.blur(), 0)
  59. }
  60. // 清空图标
  61. const inputRef = ref()
  62. const clearIcon = () => {
  63. valueIcon.value = ''
  64. emit('update:iconValue', '')
  65. setTimeout(() => inputRef.value.blur(), 0)
  66. }
  67. // 监听搜索框值
  68. const inputValue = ref('')
  69. const customIcons: { [key: string]: any } = Icons
  70. const iconsList = computed((): { [key: string]: any } => {
  71. if (!inputValue.value) return Icons
  72. let result: { [key: string]: any } = {}
  73. for (const key in customIcons) {
  74. if (key.toLowerCase().indexOf(inputValue.value.toLowerCase()) > -1) result[key] = customIcons[key]
  75. }
  76. return result
  77. })
  78. </script>
  79. <style scoped lang="scss">
  80. @import './index.scss';
  81. </style>