vue3 svg图标渲染

646 阅读1分钟

当我们有很多svg图标,并且不想使用img标签依次去渲染的时候,可以考虑封装为SvgIcon,可以直接在引用组件时定义svg图标的大小和颜色

按以下步骤进行配置即可。

1.svg图标文件

我的svg图标文件在.src/assets/svg目录下

image.png

2.创建SvgIcon.vue公共组件

这个组件内会展示传入的svg图标

<template>
  <svg
    aria-hidden="true"
    :color="color"
    :width="size"
    :height="size"
  >
    <use
      :xlink:href="symbolId"
    />
  </svg>
</template>

<script setup lang="ts">
import { computed } from 'vue'
const props = defineProps({
  // 在src/assets/svg目录下svg图标的名字
  name: {
    type: String,
    required: true
  },
  // 前缀,和vite.config.ts中配置的名称一致
  prefix: {
    type: String,
    default: 'icon'
  },
  // 图标的颜色
  color: {
    type: String,
    default: '#262626'
  },
  // 图标的大小
  size: {
    type: String,
    default: '16px'
  }
})

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

<style scope>
  .svg-icon {
    width: 18px;
    height: 18px;
    color: #333;
    fill: currentcolor;
  }
  </style>

3.在vite.config.ts中做配置

首先需要安装vite-plugin-svg-icons

yarn add vite-plugin-svg-icons -D

vite.config.ts配置

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

plugins: [
  createSvgIconsPlugin({
      // 指定需要缓存的图标文件夹
        iconDirs: [path.resolve(__dirname, './src/assets/svg')],
        // 指定symbolId格式
        symbolId: 'icon-[dir]-[name]'
      })
]

4.在main.ts中引入

import 'virtual:svg-icons-register'

5.使用组件

<SvgIcon name="password" color="#666" />

注意: svg图标文件里的颜色不能写死,查看fill后的是不是currentColor,如果不是,改为fill="currentColor"即可。