在vue3中使用vite-plugin-svg-icons插件来加载svg图标

更新于 2023-12-08 20:45 208
专栏: 前端文章 标签: vue

将所有svg图标存放在src/assets/svg-icons目录中

安装组件

  1. pnpm install vite-plugin-svg-icons -D

main.ts引入

  1. import 'virtual:svg-icons-register'

在vite.config.ts加入

  1. import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
  2. // 插件中加入这个代码
  3. [
  4. // ...
  5. createSvgIconsPlugin({
  6. iconDirs: [path.resolve(process.cwd(), 'src/assets/svg-icons')],
  7. symbolId: '[name]',
  8. }),
  9. // ...
  10. ]

定义组件

  1. <script>
  2. import { computed, defineComponent } from 'vue'
  3. function compatibleName(inputString) {
  4. // 使用正则表达式替换所有的冒号
  5. const resultString = inputString.replace(/:/g, '-')
  6. return resultString
  7. }
  8. export default defineComponent({
  9. name: 'SvgIcon',
  10. props: {
  11. icon: {
  12. type: String,
  13. required: true,
  14. },
  15. className: {
  16. type: String,
  17. default: '',
  18. },
  19. },
  20. setup(props) {
  21. const symbolId = computed(() => `#${compatibleName(props.icon)}`)
  22. const svgClass = computed(() => {
  23. if (props.className)
  24. return `svg-icon ${props.className}`
  25. return 'svg-icon'
  26. })
  27. return { symbolId, svgClass }
  28. },
  29. })
  30. </script>
  31. <template>
  32. <svg :class="svgClass" aria-hidden="true">
  33. <use class="svg-use" :href="symbolId" />
  34. </svg>
  35. </template>
  36. <style scope>
  37. .svg-icon {
  38. width: 1em;
  39. height: 1em;
  40. fill: currentColor;
  41. overflow: hidden;
  42. }
  43. </style>

引用组件

  1. import { SvgIcon } from '@/components/common'

template

  1. <div>
  2. <SvgIcon icon="mingcute-more-1-fill" style="color: pink;height: 50px;width: 50px;" />
  3. </div>

参考:https://blog.csdn.net/weixin_53731501/article/details/125478380

BLOG

搜索文章