在开发项目的时候经常会用到svg矢量图,而且我们使用SVG以后,页面上加载的不再是图片资源,
这对页面性能来说是个很大的提升,而且我们SVG文件比img要小的很多,放在项目中几乎不占用资源。
一,安装SVG依赖插件
pnpm install vite-plugin-svg-icons -D
二,在vite.config.ts中配置插件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
export default () => {
return {
plugins: [
createSvgIconsPlugin({
// Specify the icon folder to be cached
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
// Specify symbolId format
symbolId: 'icon-[dir]-[name]',
}),
],
}
}
三,入口文件导入
import 'virtual:svg-icons-register'
四,在项目中引入SVG
4.1 在阿里字体图标库中复制svg代码
4.2 在src/assets文件下新建文件夹icons
然后新建一个叫做flower.svg的文件,把我们复制的svg代码放入该文件中。
接下来我们测试。svg引入是否成功。
<template>
<div>
<div class="box">SVG测试</div>
<!--测试SVG图标使用-->
<!--svg:图标外层容器节点,内部需要与use标签结合使用-->
<svg style="width: 30px; height: 30px">
<!-- xlink:href执行用哪一个图标,属性值务必 #icon 图标名字 -->
<!-- use标签fill属性可以设置图标的颜色 -->
<use xlink:href="#icon-flower" fill="red"></use>
</svg>
</div>
</template>
五、svg封装为全局组件
因为项目很多模块需要使用图标,因此把它封装为全局组件!!!
在src/components目录下创建一个SvgIcon组件:代表如下
路径为src\components\SvgIcon\index.vue
<template>
<div>
<svg :style="{ width: width, height: height }">
<use :xlink:href="prefix + name" :fill="color"></use>
</svg>
</div>
</template>
<script setup lang="ts">
defineProps({
//xlink:href属性值的前缀
prefix: {
type: String,
default: '#icon-'
},
//svg矢量图的名字
name: String,
//svg图标的颜色
color: {
type: String,
default: ""
},
//svg宽度
width: {
type: String,
default: '16px'
},
//svg高度
height: {
type: String,
default: '16px'
}
})
</script>
<style scoped></style>
在src文件夹目录下创建一个index.ts文件:用于注册components文件夹内部全部全局组件!!!
import SvgIcon from './SvgIcon/index.vue';
import type { App, Component } from 'vue';
const components: { [name: string]: Component } = { SvgIcon };
export default {
install(app: App) {
Object.keys(components).forEach((key: string) => {
app.component(key, components[key]);
})
}
}
在入口文件引入src/index.ts文件,通过app.use方法安装自定义插件
import gloablComponent from './components/index';
app.use(gloablComponent);