一、Vue2中svg图标组件的封装
1、安装“svg-sprite-loader”第三方库
npm install svg-sprite-loader
如果存在版本问题,可以安装下面的版本
2、创建svg文件夹存放图标文件(图标可以去阿里巴巴矢量图标库自行下载)。
3、vue.config.js中增加处理svg文件的配置(!配置中的路径需和存放svg的路径保持一致)。
module.exports = defineConfig({
transpileDependencies: true,
chainWebpack(config) {
// 配置 svg-sprite-loader
config.module
.rule('svg')
.exclude.add(resolve('src/assets/icons'))
.end()
config.module
.rule('icons')
.test(/.svg$/)
.include.add(resolve('src/assets/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end()
}
})
4、封装SvgIcons组件(可根据自身需求进行调整)
<script>
export default {
name: "SvgIcon",
props: {
// 属性值前缀
prefix: {
type: String,
default: '#icon-'
},
// 图标名称
name: {
type: String,
default: ''
},
// 图标颜色
color: {
type: String,
default: ''
},
// 图标宽度
width: {
type: String,
default: ''
},
// 图标高度
height: {
type: String,
default: ''
}
}
}
</script>
<template>
<svg :style="{width: width, height: height}">
<use :xlink:href="prefix + name" :fill="color"></use>
</svg>
</template>
<style scoped>
</style>
5、创建处理svg文件的入口文件,负责加载svg文件并将SvgIcons组件挂载到Vue实例上(该文件我创建在icons目录下,和svg文件夹同级)。
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'
Vue.component('svg-icon', SvgIcon)
/**
* require.context 的参数说明
* './svg' 代表要查找的文件路径
* false 代表是否查找子目录
* /.svg$/ 代表要匹配文件的正则
*
*/
const svg = require.context('./svg', false, /.svg$/)
const requireAll = (requireContext) => requireContext.keys().map(requireContext)
requireAll(svg)
6、main.js引入上面创建的入口文件
// 引入svg
import '@/assets/icons/index.js'
7、使用SvgIcon组件
<template>
<div id="app">
<svg-icon name="phone" color="red" width="30px" height="30px"></svg-icon>
</div>
</template>
<script>
export default {
name: 'App',
}
</script>
<style>
</style>
二、 Vue3中svg图标组件的封装
1、安装“vite-plugin-svg-icons”第三方库
如果存在版本问题,可以安装下面的版本
2、创建icons文件夹存放svg文件
3、vite.config.ts中增加处理svg文件的配置(注意配置中的路径,需和svg文件的存放位置保持一致)
import { defineConfig } from 'vite';
import path from 'path'
import {createSvgIconsPlugin} from "vite-plugin-svg-icons";
export default defineConfig({
plugins: [
createSvgIconsPlugin({
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
symbolId: 'icon-[dir]-[name]',
}),
],
});
4、创建SvgIcon组件(可根据自身需求进行调整)
<!--svg图标公用组件-->
<script setup lang="ts">
// 接受父组件传递过来的参数
defineProps({
// 属性值前缀
prefix: {
type: String,
default: '#icon-'
},
// 图标名称
name: {
type: String,
default: ''
},
// 图标颜色
color: {
type: String,
default: ''
},
// 图标宽度
width: {
type: String,
default: ''
},
// 图标高度
height: {
type: String,
default: ''
}
})
</script>
<template>
<svg :style="{width: width, height: height}">
<use :xlink:href="prefix + name" :fill="color"></use>
</svg>
</template>
<style scoped>
</style>
5、main.ts中新增svg插件需要的配置代码
// svg插件需要配置代码
import 'virtual:svg-icons-register'
6、 使用SvgIcon组件
<script setup lang="ts">
import SvgIcon from './SvgIcon/index.vue';
</script>
<template>
<div>
<svg-icon name="phone" color="red" width="30px" height="30px"></svg-icon>
</div>
</template>
<style scoped>
</style>