1、SVG图标配置
- 在开发项目的时候经常会用到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]',
}),
],
}
}
注:svg图标必须放在src/assets/icons的文件夹中
入口文件main导入
import 'virtual:svg-icons-register'
2、svg封装为全局组件
<template>
<svg :style="{ width: width, height: height }">
<use :xlink:href="prefix + name" :fill="color"></use>
</svg>
</template>
<script setup lang="ts">
// ts写法
withDefaults(
defineProps<{
prefix?: string
name?: string
color?: string
width?: string
height?: string
}>(),
{
prefix: '#icon-',
width: '16px',
height: '16px',
},
)
// 非ts写法
// defineProps({
// // 矢量图的前缀
// prefix: {
// type: String,
// default: '#icon-',
// },
// // 矢量图的名字
// name: {
// type: String,
// },
// //svg图标的颜色
// color: {
// type: String,
// default: '',
// },
// //svg宽度
// width: {
// type: String,
// default: '16px',
// },
// //svg高度
// height: {
// type: String,
// default: '16px',
// },
// })
</script>
<style scoped lang="scss"></style>
在src文件夹目录components
下创建一个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/components/index.ts文件,通过app.use方法安装自定义插件\
import gloablComponent from './components/index';
app.use(gloablComponent);