效果展示
vite-svg-loader
使用 vite-svg-loader 的目的是将 SVG 文件转换为 可直接交互的 Vue 组件
为什么选择vite-svg-loader:
- 它配置比较简单,可以快速的接入项目
- 在vite官方的社区中,推荐了这款插件
安装
npm install vite-svg-loader --save-dev
在 vite.config 中注册
参考vite-svg-loader仓库README.md
- vite插件配置loader
import svgLoader from 'vite-svg-loader'
export default defineConfig({
plugins: [vue(), svgLoader()]
})
- 开启svgo
SVGO(SVG Optimizer)是一个用于优化 SVG 文件的工具。它通过移除不必要的元素、压缩数据和简化结构来减少文件大小,从而提高加载速度和性能
svgLoader({
svgoConfig: {
multipass: true
}
})
定义SvgIcon组件
创建动态组件
在src -> component -> svg目录下新建 SvgIcon.vue文件,内容如下:
<template>
<component :is="svgComponent" :width="width" :height="height" />
</template>
<script setup>
import { defineAsyncComponent, computed } from 'vue';
const props = defineProps({
name: {
type: String,
required: true
},
width: {
type: [String, Number],
default: '20'
},
height: {
type: [String, Number],
default: '20'
}
});
const svgComponent = computed(() => dynamicImport(props.name));
const dynamicImport = (iconName) => {
return defineAsyncComponent(() =>
import(`@/assets/svgIcons/${iconName}.svg`)
// 导入资源不存在的时候,兜底展示资源
// .catch(() => import(`@/assets/svgIcons/notfound.svg`))
);
};
</script>
导入svg图片
在src -> assets -> svgIcons目录下,导入相关svg图像。这里建议去阿里巴巴矢量库下载.
我这里的目录内容如下:
使用SvgIcon组件动态导入svg图片
- 代码如下
<template>
<div>
<SvgIcon :name="selected" width="20" height="20" />
<div>
<select v-model="selected">
<option disabled value="">Please select one</option>
<option>github</option>
<option>wechat</option>
<option>qq</option>
</select>
</div>
</div>
</template>
<script setup>
import SvgIcon from "@/components/svg/SvgIcon.vue";
import { ref } from "vue";
const selected = ref("github");
</script>
<style scoped></style>
- 最终效果如下