封装svg 组件
在components 新建组件
目录:components/SvgIcon/index.vue
封装:
<script setup>
import { computed } from 'vue'
const props = defineProps({
iconClass: {
type: String,
required: true
},
className: {
type: String,
default: ''
}
})
const iconName = computed(() => {
return `#icon-${props.iconClass}`
})
const svgClass = computed(() => {
if (props.className) {
return 'svg-icon ' + props.className
} else {
return 'svg-icon'
}
})
</script>
<template>
<svg :class="svgClass" aria-hidden="true">
<use :xlink:href="iconName" />
</svg>
</template>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
.svg-external-icon {
background-color: currentColor;
mask-size: cover !important;
display: inline-block;
}
</style>
注册组件:
目录:/src/icons/index.js
import SvgIcon from '@/components/SvgIcon/index.vue'
export default {
install(app) {
const components = { SvgIcon }
Object.keys(components).forEach((key) => {
app.component(key, components[key])
})
}
}
安装插件
插件1:vite-plugin-svg-icons
npm install vite-plugin-svg-icons
插件2:fast-glob
npm install fast-glob
注册全局组件
在main.js 文件引入相关文件
import 'virtual:svg-icons-register'
import SvgIcon from '@/icons/index.js'
app.use(SvgIcon)
配置打包文件
在vite.config.js
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
export default defineConfig({
plugins: [
createSvgIconsPlugin({
// 指定要缓存.svg文件的文件夹
iconDirs: [path.resolve(process.cwd(), 'src/icons/svg')],
symbolId: 'icon-[dir]-[name]'
})
],
})