SVG组件代码
组件路径:src/components/SvgIcon
<template>
<div
v-if="isExternal"
:style="styleExternalIcon"
class="svg-external-icon svg-icon"
v-bind="$attrs"
/>
<!--多层组件监听 Vue2:v-bind="$attrs" v-on="$listeners" Vue3:v-bind="$attrs"-->
<svg v-else :class="svgClass" aria-hidden="true" v-bind="$attrs">
<use :xlink:href="iconName" />
</svg>
</template>
<script>
import { isExternal } from "@/utils/validate";
export default {
name: "SvgIcon",
props: {
// svg 文件名,不要加上后缀
iconClass: {
type: String,
required: true
},
// svg图标样式类
className: {
type: String,
default: ""
}
},
computed: {
isExternal() {
return isExternal(this.iconClass);
},
iconName() {
return `#icon-${this.iconClass}`;
},
svgClass() {
if (this.className) {
return "svg-icon " + this.className;
} else {
return "svg-icon";
}
},
styleExternalIcon() {
return {
mask: `url(${this.iconClass}) no-repeat 50% 50%`,
"-webkit-mask": `url(${this.iconClass}) no-repeat 50% 50%`
};
}
}
};
</script>
<style scoped>
.svg-icon {
width: 1.1em;
height: 1.1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
.svg-external-icon {
background-color: currentColor;
mask-size: cover !important;
display: inline-block;
}
</style>
全局引入挂载
组件路径:src/icons/index.js
import { createApp } from "vue";
import App from "../App.vue";
// svg component 引入svg组件
import SvgIcon from "@/components/SvgIcon";
const app = createApp(App);
// register globally 注册全局使用
app.component("svg-icon", SvgIcon);
const req = require.context("./svg", false, /\.svg$/);
const requireAll = requireContext => requireContext.keys().map(requireContext);
requireAll(req);
在mian.js中进行引入
import "./icons"
出现的警告信息如下:
解决方案
将src/icons/index.js全局挂载的方法写到main.js中去,代码如下:
// 引入SvgIcon组件
import SvgIcon from "@/components/SvgIcon";
const req = require.context("./icons/svg", false, /\.svg$/);
const requireAll = requireContext => requireContext.keys().map(requireContext);
requireAll(req);
// register globally 注册全局使用
app.component("svg-icon", SvgIcon);
这样就可以解决问题啦,希望对大家有帮助额