在开发项目的时候,经常会用到svg矢量图,而且我们使用svg以后,页面上加载的不在是图片资源,这对页面性能来说是很大的提升,SVG比img小很多,占用资源很少
官方支持vbenjs/vite-plugin-svg-icons - Vite 中文文档
安装svg依赖插件
pnpm install vite-plugin-svg-icons -D
在vite.config.ts中配置插件
plugins: [
vue(),
createSvgIconsPlugin({
// Specify the icon folder to be cached
iconDirs: [path.resolve(process.cwd(), "src/assets/icons")],
// Specify symbolId format
symbolId: "icon-[dir]-[name]",
}),
],
在main.ts中导入
import 'virtual:svg-icons-register'
启动报错问题:解决无法找到 'fast-glob' 包的问题
pnpm install fast-glob --save-dev
在页面中使用
图标来源可以从 https://www.iconfont.cn/ 获取
<!-- svg 测试,可以填充大小颜色-->
<svg style="width: 30px; height: 30px">
<use xlink:href="#icon-query" fill="#b83b5e"></use>
</svg>
抽提为组件
在components下新建SvgIcon文件夹,在SvgIcon下创建index.vue,内容如下
<template>
<!-- svg 测试 属性一样简写-->
<svg :style="{ width, height }">
<use :xlink:href="prefix + name" :fill="color"></use>
</svg>
</template>
<script setup lang="ts">
import { defineProps } from "vue";
//接受父组件传递过来的参数
defineProps({
//xlink:href 属性值前缀
prefix: {
type: String,
default: "#icon-",
},
//图标名称
name: String,
//图标颜色
color: {
type: String,
default: "",
},
//图标宽度
width: {
type: String,
default: "16px",
},
//图标高度
height: {
type: String,
default: "16px",
},
});
</script>
<style scoped></style>
手动注册为全局组件main.ts
// 注册为全局组件
import SvgIcon from "@/components/SvgIcon/index.vue";
app.component("SvgIcon", SvgIcon);
自定义注册为全局组件
参考 插件 | Vue.js
在components下添加index.ts,内容如下
//引入项目中全局组件
import SvgIcon from "@/components/SvgIcon/index.vue";
//多个组件放到对象中去 key value 名称一致省略
const GlobalComp = { SvgIcon };
console.log(Object.keys(GlobalComp));
//对外暴露插件对象
export default {
install(app: any) {
console.log("------plugin------");
Object.keys(GlobalComp).forEach((key) => {
app.component(key, GlobalComp[key]);
});
},
};
在main.ts中注册
//插件机制
import globalComponent from "@/components";
app.use(globalComponent);