Webアプリ/制作で必ずどこかしらに使われているアイコンをVueで管理する時のTipsを紹介したいと思います!
まずsvgアイコンを格納しておくファイルから解説していきます。
// svg.vue
<template>
// svgタグを追加
<svg
enable-background="new 0 0 100 100"
viewBox="0 0 100 100"
xmlns="http://www.w3.org/2000/svg"
>
// pathの中のdを配列の中から選ぶことで任意のアイコンが表示される
<path v-for="(d, index) in icons[icon]" :key="index" :d="d" />
</svg>
</template>
<script>
export default {
name: "SvgIcon",
props: {
icon: {
type: String,
// デフォルトを指定
default: "favorite",
},
},
computed: {
icons() {
// アイコンの配列を作成していく
const icons = {
favorite: [
"M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z",
],
account: [
"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z",
],
close: [
"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z",
],
};
return icons;
},
},
};
</script>
Googleが推奨しているマテリアルアイコン から好きなアイコンをSVGでダウンロードした後にpathタグの中のd=のあとを配列へコピーしていきます。
// hellowworld.vue
<template>
<div class="hello">
<div class="width">
// svg.vueの配列に入れた呼び出したい値を入れていく
<svg-icon :icon="'favorite'" />
</div>
<div class="width">
<svg-icon :icon="'account'" />
</div>
<div class="width">
// svg.vueの配列に入れた呼び出したい値を入れていく
<svg-icon :icon="'close'" />
</div>
</div>
</template>
<script>
// コンポーネントをインポート
import SvgIcon from "@/components/svg";
export default {
name: "HelloWorld",
components: {
SvgIcon,
},
props: {
msg: String,
},
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.hello {
display: flex;
}
.width {
width: 33.333%;
}
</style>