LoginSignup
2
2

More than 1 year has passed since last update.

【Vue.js】SVGをコンポーネント化する方法

Posted at

自作のSVGファイルをコンポーネントとして使いたくなる場面があるかもしれません。

方法その1 普通にやる

SVGをそのままtemplateに書いてしまえばコンポーネントとして使うことができます。

components/icons/logo.vue
<template>
  <svg xmlns="http://www.w3.org/2000/svg">
    <!--何か -->
  </svg>
</template>
App.vue
<template>
  <icon-logo />
</template>

<script setup lang="ts">
import IconLogo from './components/icons/IconLogo.vue'
</script>

これで表示できます。

image.png

方法その2 unplugin-icons

先の方法だと、わざわざSVGファイルを開いてcomponents内にコピペする必要があるため、なかなか面倒です。
そこで、unplugin-iconsというパッケージを使う方法を紹介します。

まずはインストール

npm i -D unplugin-icons

次に設定ですが、今回はViteでやってみます。

vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import Icons from 'unplugin-icons/vite'
import { FileSystemIconLoader } from 'unplugin-icons/loaders'

export default defineConfig({
  plugins: [
    vue(),
    Icons({
      customCollections: {
        svg: FileSystemIconLoader('src/assets/svg')
      },
    })
  ]
})

これで、src/assets/icons/ディレクトリにSVGファイルを配置するだけで、コンポーネントとして呼び出すことができるようになります。
~icons/icons/<ファイル名> としてimportすることができます。

App.vue
<template>
  <icon-logo />
</template>

<script setup lang="ts">
import IconLogo from '~icons/icons/logo'
</script>

image.png

設定したディレクトリにファイルを置くだけで使えるので、なかなか便利です。
unplugin-iconsには他にも色々な機能があるので、是非調べてみてください。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2