index.vue 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <template>
  2. <i v-if="isShowIconSvg" class="el-icon" :style="setIconSvgStyle">
  3. <component :is="getIconName" />
  4. </i>
  5. <div v-else-if="isShowIconImg" :style="setIconImgOutStyle">
  6. <img :src="getIconName" :style="setIconSvgInsStyle" />
  7. </div>
  8. <svg v-else-if="isShowLocalSvg" class="svg-icon icon" :style="setIconImgOutStyle">
  9. <use :href="`#${getIconName}`" />
  10. </svg>
  11. <i v-else :class="getIconName" :style="setIconSvgStyle" />
  12. </template>
  13. <script setup lang="ts" name="svgIcon">
  14. import { computed } from 'vue';
  15. // 定义父组件传过来的值
  16. const props = defineProps({
  17. // svg 图标组件名字
  18. name: {
  19. type: String,
  20. },
  21. // svg 大小
  22. size: {
  23. type: Number,
  24. default: () => 14,
  25. },
  26. // svg 颜色
  27. color: {
  28. type: String,
  29. },
  30. });
  31. // 在线链接、本地引入地址前缀
  32. const linesString = ['https', 'http', '/src', '/assets', 'data:image', import.meta.env.VITE_PUBLIC_PATH];
  33. // 获取 icon 图标名称
  34. const getIconName = computed(() => {
  35. return props?.name;
  36. });
  37. // 用于判断 element plus 自带 svg 图标的显示、隐藏
  38. const isShowIconSvg = computed(() => {
  39. return props?.name?.startsWith('ele-');
  40. });
  41. // 用于判断在线链接、本地引入等图标显示、隐藏
  42. const isShowIconImg = computed(() => {
  43. return linesString.find((str) => props.name?.startsWith(str));
  44. });
  45. const isShowLocalSvg = computed(() => {
  46. return props?.name?.startsWith('local-');
  47. });
  48. // 设置图标样式
  49. const setIconSvgStyle = computed(() => {
  50. return `font-size: ${props.size}px;color: ${props.color};`;
  51. });
  52. // 设置图片样式
  53. const setIconImgOutStyle = computed(() => {
  54. return `width: ${props.size}px;height: ${props.size}px;display: inline-block;overflow: hidden;`;
  55. });
  56. // 设置图片样式
  57. const setIconSvgInsStyle = computed(() => {
  58. const filterStyle: string[] = [];
  59. const compatibles: string[] = ['-webkit', '-ms', '-o', '-moz'];
  60. compatibles.forEach((j) => filterStyle.push(`${j}-filter: drop-shadow(${props.color} 30px 0);`));
  61. return `width: ${props.size}px;height: ${props.size}px;position: relative;left: -${props.size}px;${filterStyle.join('')}`;
  62. });
  63. </script>