vue里组件化引入svg图标的方式

配置好后可以轻松从iconfont导入svg图标或者任意svg图标。
参考:https://blog.csdn.net/weixin_39729729/article/details/137348970

https://blog.csdn.net/CMDN123456/article/details/139854354

官网https://www.iconfont.cn/help/detail?spm=a313x.help_detail.i1.d8d11a391.550b3a81PTK8cM&helptype=code

重点是 symbol 引用,以下是vite配置使用的方式:

  1. 首先安装 pnpm add vite-plugin-svg-icons -D,然后配置:

    // vite.config.ts
    import { resolve } from "path"
    import { createSvgIconsPlugin } from "vite-plugin-svg-icons"
    
    const pathSrc = resolve(__dirname, "src")
    
    export default defineConfig({
      ...
      plugins: [
        createSvgIconsPlugin({
          // 指定需要缓存的图标文件夹,也就是项目实际存放svg图标的文件夹
          iconDirs: [resolve(pathSrc, "assets/icons")],
          // 指定symbolId格式
          symbolId: "icon-[name]",
        }),
      ]
    })
    
  2. 项目的main.ts中导入:

    // 本地SVG图标
    import "virtual:svg-icons-register"
    
  3. 参考这个组件 SvgIcon 写法,需要使用iconfont图标时,直接在调用组件时传入 :icon-class=“图标名” 即可,例如:<svg-icon :icon-class=" isFullscreen ? ‘fullscreen-exit’ : ‘fullscreen’ " /> (fullscreen-exit和fullscreen是两个图标)。图标存放地址,例如:src/assets/icons/fullscreen.svg

<!-- SvgIcon.vue -->
<template>
  <svg
    aria-hidden="true"
    class="svg-icon"
    :style="'width:' + size + ';height:' + size"
  >
    <use :xlink:href="symbolId" :fill="color" />
  </svg>
</template>

<script setup lang="ts">
const props = defineProps({
  prefix: {
    type: String,
    default: "icon",
  },
  iconClass: {
    type: String,
    required: false,
    default: "",
  },
  color: {
    type: String,
    default: "",
  },
  size: {
    type: String,
    default: "1em",
  },
});

const symbolId = computed(() => `#${props.prefix}-${props.iconClass}`);
</script>

<style scoped>
.svg-icon {
  display: inline-block;
  width: 1em;
  height: 1em;
  overflow: hidden;
  vertical-align: -0.15em; /* 因icon大小被设置为和字体大小一致,而span等标签的下边缘会和字体的基线对齐,故需设置一个往下的偏移比例,来纠正视觉上的未对齐效果 */
  outline: none;
  fill: currentcolor; /* 定义元素的颜色,currentColor是一个变量,这个变量的值就表示当前元素的color值,如果当前元素未设置color值,则从父元素继承 */
}
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值