vue3+vite 中自定义 svg 图片 icon

发布时间 2023-05-28 20:18:52作者: 攻城Alone

  关于 vue3 + vite 开发一个管理后台,并在后台中使用 自定义的 svg 图片左右路由icon

安装依赖

  • npm i vite-plugin-svg-icons --D

或者

  • yarn add vite-plugin-svg-icons --D 等其它的安装工具

配置相关的 vite 配置

  import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

  export default () => {
    return {
      plugins: [
        createSvgIconsPlugin({
          // 指定需要缓存的图标文件夹
          iconDirs: [path.resolve(process.cwd(), 'src/icons')],
          // 指定symbolId格式
          symbolId: 'icon-[dir]-[name]'
        })
      ]
    }
  }

引入相关的依赖并创建组件

  • main.ts

      import 'virtual:svg-icons-register'
    
  • 自定义组件 同时使用 element plus 图标

      <template>
        <template v-if="getIconName.includes('ele-')">
         <i
            :class="getIconName"
            class="el-icon sub-el-icon"
          >
            <component :is="getIconName" />
          </i>
        </template>
        <template v-else>
          <svg aria-hidden="true" class="svg-icon" :width="props.size" :height="props.size">
            <use :xlink:href="symbolId" :fill="props.color" />
          </svg>
        <template>
      </template>
    
      <script setup>
      import { computed } from 'vue'
      const props = defineProps({
        prefix: {
          type: String,
          default: 'icon'
        },
        name: {
          type: String,
          required: true
        },
        color: {
          type: String,
          default: '#333'
        },
        size: {
          type: String,
          default: '1em'
        }
      })
    
      const symbolId = computed(() => `#${props.prefix}-${props.name}`)
      const getIconName = computed(() => {
        return props?.name
      })
      </script>
    
    <style lang="scss" scoped>
      .sub-el-icon {
        color: currentColor;
        display: inline-block;
        width: 14px;
        height: 14px;
        font-size: 16px;
        margin-right: 5px;
      }
    </style>
    
    • 全局注册
      import svgIcon from "@/components/SvgIcon/index.vue"
    
      createApp(App)
      .component('svg-icon', svgIcon)
      .mount('#app')
    
  • 使用

      <svg-icon v-if="props.icon" :name="props.icon" />