项目引用背景
vue3+ts
本人使用的vue项目 地址:ZY/vue3-composition-admin
svgicon.ts
import SvgIcon from '@/components/SvgIcon/Index.vue'
export const svgPlugin: any = {
install: function(vue: any, options: any) {
if (
options &&
options.imports &&
Array.isArray(options.imports) &&
options.imports.length > 0
) {
// 按需引入图标
const { imports } = options
imports.forEach((name: any) => {
require(`@/assets/icons/svg/${name}.svg`)
})
} else {
// 全量引入图标
const ctx = require.context('@/assets/icons/svg', false, /\.svg$/)
ctx.keys().forEach(path => {
const temp = path.match(/\.\/([A-Za-z0-9\-_]+)\.svg$/)
if (!temp) return
const name = temp[1]
require(`@/assets/icons/svg/${name}.svg`)
})
}
vue.component('SvgIcon', SvgIcon)
// vue.component(SvgIcon.name, SvgIcon)
}
}
export default function svgComponent(app: any) {
app.use(svgPlugin, {
imports: []
})
}
SvgIcon/index.vue
<!--
* @Description:
* @Version: 2.0
* @Autor: ycw
* @Date: 2021-12-31 09:36:51
* @LastEditors: ycw
* @LastEditTime: 2022-01-06 10:43:36
-->
<template>
<svg
:class="svgClass"
aria-hidden="true"
>
<use
:xlink:href="iconName"
:fill="color"
/>
</svg>
</template>
<script lang="ts">
import { computed, defineComponent } from 'vue'
export default defineComponent({
props: {
iconClass: {
type: String,
required: true
},
className: {
type: String,
default: ''
},
color: {
type: String,
default: ''
}
},
setup(props) {
return {
iconName: computed(() => `#icon-${props.iconClass}`),
svgClass: computed(() => {
if (props.className) {
return `svg-icon ${props.className}`
}
return 'svg-icon'
})
}
}
})
</script>
<style scope lang="scss">
.sub-el-icon,
.nav-icon {
display: inline-block;
font-size: 15px;
margin-right: 12px;
position: relative;
}
.svg-icon {
width: 1em;
height: 1em;
position: relative;
fill: currentColor;
vertical-align: -2px;
}
</style>