Icon.vue 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <template>
  2. <span
  3. class="icon"
  4. v-html="svgContent"
  5. :style="{ width: size + 'px', height: size + 'px', color }"
  6. />
  7. </template>
  8. <script setup>
  9. import { ref, watchEffect } from 'vue'
  10. const props = defineProps({
  11. name: { type: String, required: true }, // 图标名,如 download → download.svg
  12. size: { type: [Number, String], default: 24 },
  13. color: { type: String, default: '' }
  14. })
  15. const svgContent = ref('')
  16. // 使用 Vite 的 glob 导入所有图标
  17. const modules = import.meta.glob('@/assets/icons/*.svg', { as: 'raw' })
  18. watchEffect(async () => {
  19. const path = `/src/assets/icons/${props.name}.svg`
  20. const loader = modules[path]
  21. if (loader) {
  22. const raw = await loader()
  23. // 替换 fill="..." 为 fill="currentColor",使颜色可控
  24. svgContent.value = raw.replace(/fill="[^"]*"/g, 'fill="currentColor"')
  25. } else {
  26. console.warn(`[Icon] SVG not found: ${props.name}`)
  27. svgContent.value = ''
  28. }
  29. })
  30. </script>
  31. <style scoped>
  32. .icon {
  33. display: inline-flex;
  34. align-items: center;
  35. justify-content: center;
  36. color: inherit;
  37. }
  38. </style>