在日常开发中,框架中的图标库可能不能满足我们的开发需求,或者自己设计svg图标,所以我们经常会在项目中引入svg图标。以下是svg图标在我们项目中的使用过程。
1、项目安装依赖包 svg-sprite-loader
npm install svg-sprite-loader --save-dev
2、项目src目录下的components文件夹下创建svgIcon文件夹,svgIcon文件夹下创建svg文件夹,将下载svg图标放入svg文件夹中。
3、配置vue.config.js
module.exports = {
......
chainWebpack: (config) => {
// svg
config.module
.rule('svg')
.exclude.add(resolve('src/components/svgIcon/svg')) //svg图标存放位置
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/components/svgIcon/svg')) //svg图标存放位置
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end()
}
}
4、在svgIcon文件夹下创建index.vue文件,index.vue组件代码如下:
<template>
<svg :class="svgClass" aria-hidden="true">
<use :xlink:href="iconName"></use>
</svg>
</template>
<script setup>
import { computed } from 'vue'
const props = defineProps({
iconClass: {
type: String,
required: true
},
className: {
type: String,
default: ''
}
})
const iconName = computed(()=>{
return `#icon-${props.iconClass}`
})
const svgClass = computed(()=>{
if (props.className) {
return 'svg-icon ' + props.className
} else {
return 'svg-icon'
}
})
const req = require.context('@/icons/svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
</script>
<style lang="scss" scoped>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>
5、在入口文件引入svgIcon组件,并注册
// 引入svg
import SvgIcon from '@/components/svgIcon/index.vue'
// 注册组件
app.component('svg-icon', SvgIcon)
6、使用
<svg-icon className="icon-password" icon-class="password"></svg-icon>
效果如下:
以上就是vue3中使用svg图标的过程了~~~