Vue3 中使用iconfont svg圖標

Vue3使用一段時間以后,感覺比Vue2版本提升很多。下面記錄一下如何在Vite+Vue3項目中無痛使用任何類型的svg圖標。

  1. 安裝vbenjs/vite-plugin-svg-icons: Vite Plugin for fast creating SVG sprites. (github.com)
    這個組件的作用是把多個svg生成雪碧圖方便調(diào)用

  2. vite.config.js設(shè)置,注意更換為你自己的svg文件夾路徑

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import path from 'path';
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
 plugins: [
    vue(),
    //svg
    createSvgIconsPlugin({
      // 指定需要緩存的圖標文件夾
      iconDirs: [path.resolve(process.cwd(), 'src/assets/svg')],
      // 指定symbolId格式
      symbolId: 'icon-[dir]-[name]',

      /**
       * 自定義插入位置
       * @default: body-last
       */
      inject: 'body-last' | 'body-first',

      /**
       * custom dom id
       * @default: __svg__icons__dom__
       */
      customDomId: '__svg__icons__dom__'
    })
  ],
  1. 寫一個SvgIcon組件:
<template>
  <svg aria-hidden="true" :class="svgClass" :style="styleObject" @click="emit('on-click')">
    <use :xlink:href="symbolId" :fill="color" :stroke="color" />
  </svg>
</template>

<script>
export default {
  name: 'SvgIcon'
};
</script>

<script setup>
import { computed } from 'vue';
const props = defineProps({
  prefix: {
    type: String,
    default: 'icon'
  },
  name: {
    type: String,
    required: true
  },
  color: {
    type: String,
    default: '#fff'
  },
  clickable: {
    type: Boolean,
    default: false
  },
  size: {
    type: String,
    default: '1em'
  },
  className: {
    type: String,
    default: ''
  }
});
const symbolId = computed(() => `#${props.prefix}-${props.name}`);
const svgClass = computed(() => 'svg-icon ' + props.className || '');
const styleObject = computed(() => {
  return {
    width: props.size,
    height: props.size,
    cursor: props.clickable ? 'pointer' : ''
  };
});
const emit = defineEmits(['on-click']);
</script>

  1. main.js中注冊此全局組件
//引入svg
import { createApp } from 'vue';
import App from './App.vue';
import 'virtual:svg-icons-register'; //這一句必須要加上
import SvgIcon from './components/SvgIcon.vue';

createApp(App).component('SvgIcon', SvgIcon).use(router).mount('#app');

5.直接下載svg至前面設(shè)定的文件夾下
svg文件不一定從iconfont下載,任何地方的都可以,保存在'src/assets/svg'目錄下

  1. 使用
  <SvgIcon :name="svg文件名(不帶后綴)" color="#93c5fd" size="3em"></SvgIcon>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容