I encountered this bug once before, and it was not recorded when it was solved.
But a good memory is not as good as a bad pen. This time I encountered it again, and it took more than an hour to check the bug again
svg imports vue project, need to rely on svg-sprite-loader
npm install svg-sprite-loader
in vue.config.js
chainWebpack(config) {
config.plugins.delete("preload"); // TODO: need test
config.plugins.delete("prefetch"); // TODO: need test
// set svg-sprite-loader
config.module
.rule("svg")
.exclude.add(resolve("src/assets/icons"))
// .add(resolve("src/assets/icons"))//如果还有其他文件夹下有,就add增加
.end();
config.module
.rule("icons")
.test(/\.svg$/)
.include.add(resolve("src/assets/icons"))
// .add(resolve("src/assets/icons"))
.end()
.use("svg-sprite-loader")
.loader("svg-sprite-loader")
.options({
symbolId: "icon-[name]" })
.end();
},
Create a new icons folder under assets
corresponding index.js
import Vue from "vue";
import SvgIcon from "@/components/SvgIcon"; // svg component
// register globally
Vue.component("svg-icon", SvgIcon);
const req = require.context("./svg", true, /\.svg$/);
const requireAll = (requireContext) =>
requireContext.keys().map(requireContext);
requireAll(req);
Create a new SvgIcon folder under the components folder
corresponding to index.vue
<template>
<svg :class="svgClass" aria-hidden="true" v-on="$listeners">
<use :xlink:href="iconName" />
</svg>
</template>
<script>
export default {
name: "SvgIcon",
props: {
iconClass: {
type: String,
required: true,
},
className: {
type: String,
default: "",
},
},
computed: {
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: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
.svg-external-icon {
background-color: currentColor;
mask-size: cover !important;
display: inline-block;
}
</style>
Mount globally in main.js
import "@/assets/icons"; // icon
import "@/components/SvgIcon"; // 自定义组件引入
Use in specific pages
<svg-icon icon-class="logo" />
The main reason why the use tag is 0 is that there is no corresponding svg-sprite-loader configured in vue.config.js
Remarks: svg tags are usually given directly by ui. If you need to define it yourself, create a new text document, copy the content, and change the suffix to .svg