Answer the question
In order to leave comments, you need to log in
Best way to make an SVG icon system?
Actually, I was going to put things in order, and do something
like There are a lot of ways to do it (I counted 7 pieces). I stopped at 2 (with the prospect of adding animation, etc.):
1. Stupidly in the forehead:<app-icon name="heart" />
<template>
<div>
<svg v-if="name ==='heart'">
...
</svg>
<svg v-else-if="name ==='like'">
...
</svg>
...
</div>
</template>
Answer the question
In order to leave comments, you need to log in
In my opinion, the best option is the one that is widely used - each icon is a separate component.
<app-icon-heart/>
<app-icon-like/>
<template>
<svg :src=`../assets/icons/${name}.svg`></svg>
</template>
<script>
export default {
props: {
name: {
type: String,
required: true
}
}
}
</script>
<v-icon name="like"/>
svg-sprite-loader
Setting up the loader
// vue.config.js
module.exports = {
...
chainWebpack: config => {
const Sprite = config.module.rule('svg-sprite')
Sprite
.test(/\.(svg)(\?.*)?$/)
.include
// указываем путь к папке с иконками что бы не было конфликтов(например со шрифтами)
.add(path.resolve(__dirname,'src/assets/icons'))
.end()
.use('file-loader')
.loader('file-loader')
.options( {
name: 'static/img/[name].[hash:8].[ext]'
})
Sprite
.use('file-loader')
.loader('svg-sprite-loader')
}
}
<template>
<svg :class="className" xmlns="http://www.w3.org/2000/svg" :style="style" v-on="$listeners">
<use :xlink:href="`#${name}`" xmlns:xlink="http://www.w3.org/1999/xlink"/>
</svg>
</template>
<script>
export default {
name: 'svg-icon',
props: {
name: {
type: String,
required: true
},
width: {
type: Number,
},
height: {
type: Number,
}
},
mounted() {
require(`@/assets/icons/${this.name}.svg`).default.url;
},
updated() {
// у меня возникали проблемы с тем что иконки не всегда отображаются, поэтому продублировал запрос к иконке
require(`@/assets/icons/${this.name}.svg`).default.url;
},
computed: {
className() {
return 'svg-icon svg-icon--' + this.name;
},
style() {
let style = {}
if (this.width) {
style.width = this.width+'px';
}
if (this.height) {
style.height = this.height+'px';
}
return style;
}
}
};
</script>
<style>
.svg-icon {
fill: currentColor;
height: 24px;
width: 24px;
stroke: none;
}
</style>
//main.js
//....
import SvgIcon from '@/components/SvgIcon
//....
Vue.use(SvgIcon, {
tagName: 'svgicon'
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question