vue3.2/Vite/Ts11: svg 图标库的封装和使用
·
Yin灏
安装 svg 依赖插件
pnpm install vite-plugin-svg-icons -D
在 vite.config.ts 中配置插件
//...
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
import path from 'path';
//...
plugins: [
createSvgIconsPlugin(
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
symbolId: 'icon-[dir]-[name]'
)
]
//...
入口文件中导入 main.ts
import 'virtual:svg-icons-register'
使用
<template>
<svg style="width:30px;height:30px">
<use xlink:href="#icon-phone" fill="red"></use>
</svg>
</template>
<script setup lang='ts'></script>
- 注:#icon-phone: #icon- 是前缀,phone 是 svg 图片名称
封装 svg 组件
- 新建 src / components / SvgIcon / index.vue
<template>
<svg :style="{width, height}">
<use :xlink:href="prefix + name" :fill="color"></use>
</svg>
</template>
<script setup lang='ts'>
defineProps({
prefix: {
type: String,
default: '#icon-'
},
name: String,
color: {
type: String,
default: ''
},
width: {
type: String,
default: '16px'
},
height: {
type: String,
default: '16px'
}
})
</script>
- 在组件中使用
<template>
<svg-icon
name="home"
color="pink"
></svg-icon>
</template>
<script setup lang='ts'>
import SvgIcon from '@/components/SvgIcon/index.vue'
</script>