1.创建utils文件夹,在utils文件夹中创建validata.js,判断图标是否为外部资源。
validata.js:
// 判断是否为外部资源
export function isExternal(path) {
return /^(https?:|mailto:|tel:)/.test(path)
}
2.在components中创建SvgIcon文件夹,在SvgIcon文件夹中创建index.vue。
index.vue:
<template>
<!-- 展示外部图标 -->
<div
v-if="isExternal"
:style="styleExternalIcon"
class="svg-external-icon svg-icon"
:class="className"
></div>
<!-- 展示内部图标 -->
<svg v-else class="svg-icon" aria-hidden="true">
<use :xlink:href="iconName"></use>
</svg>
</template>
<script setup>
import { defineProps, computed } from 'vue'
import { isExternal as external } from '@/utils/validate'
const props = defineProps({
icon: {
type: String,
required: true
},
className: {
type: String,
default: ''
}
})
// 判断当前图标是否为外部图标
const isExternal = computed(() => external(props.icon))
// 外部图标样式
const styleExternalIcon = computed(() => ({
mask: `url(${props.icon}) no-repeat 50% 50%`,
'-webket-mask': `url(${props.icon}) no-repeat 50% 50%`
}))
// 内部图标
const iconName = computed(() => `#icon-${props.icon}`)
</script>
<style lang="scss" scoped>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
.svg-external-icon {
mask-size: cover !important;
display: inline-block;
background-color: currentColor;
}
</style>
3.使用
ps:如果是iconfont上的图标,需要在public中的html引入链接,点进去有iconfont教程,请参考symbol 引用。
import SvgIcon from '@/components/SvgIcon/index.vue'
<span class="svg-container">
<svg-icon icon="yonghu-xianxing"></svg-icon>
</span>
4.全局引入
(1) 在src目录下创建icons文件夹,创建svg子文件夹放svg矢量图,并在icons文件夹下创建文件index.js。
index.js:
import SvgIcon from '@/components/SvgIcon'
// 导入所有的svg图标
const svgRequire = require.context('./svg', false, /\.svg$/)
svgRequire.keys().forEach((svgIcon) => svgRequire(svgIcon))
// console.log(svgRequire.keys())
export default (app) => {
app.component('svg-icon', SvgIcon)
}
(2) 在main.js中引入上面创建的文件,并全局挂载。
import installIcons from '@/icons'
installIcons(app)