I am a newbie on Vue. I searched various replies in stackoverflow, seems no good answer got. The SVG Icon couldn’t be rendered. Can anyone help me to figure this out?
my purpose is to use a component to load the svg more conveniently, instead of loading it one by one
all my svg are saved in /icons/svg/ folder, /icons/index.js:
import SvgIcon from '@/components/SvgIcon'
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
export default (app) => {
app.component('svg-icon', SvgIcon)
}
/components/SvgIcon/index.vue
<template>
<div v-if="isExternal" :style="styleExternalIcon" class="svg-external-icon svg-icon" v-on="$listeners" />
<svg v-else :class="svgClass" aria-hidden="true" v-on="$listeners">
<use :xlink:href="iconName" />
</svg>
</template>
<script>
import { isExternal } from '@/utils/validate'
export default {
name: 'SvgIcon',
props: {
iconClass: {
type: String,
required: true
},
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: 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>
main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from '@/router/router'
import axios from 'axios'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import '@/icons'
const app = createApp(App)
app.use(ElementPlus)
axios.defaults.baseURL = 'http://0.0.0.0:8880'
app.use(router, axios).mount('#app')
landing index.vue:
<template>
<span class="svg-container">
<svg-icon icon-class="user" />
</span>
</template>