zorroe

zorroe

在Vue3中使用插件vite-plugin-svg-icons

安裝#

npm install vite-plugin-svg-icons --save-dev

設定#

  1. vite.config.ts中進行設定

    import { defineConfig } from "vite";
    import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
    import vue from "@vitejs/plugin-vue";
    import path from "path";
    
    // https://vitejs.dev/config/
    export default defineConfig({
      plugins: [
        vue(),
        createSvgIconsPlugin({
          iconDirs: [path.resolve(process.cwd(), "src/assets/icons/svg")],
          symbolId: "icon-[dir]-[name]",
        }),
      ],
    });
    
  2. 在專案的src/assets目錄下創建icons/svg目錄並放入 svg 圖標文件image-20230711195608293

  3. main.ts中引入

    import "virtual:svg-icons-register";
    
  4. 定義組件SvgIcon.vue

    <template>
      <svg :class="svgClass" aria-hidden="true">
        <use :xlink:href="iconName" :fill="props.color" />
      </svg>
    </template>
    
    <script lang="ts" setup>
    import { computed } from "vue";
    
    const props = defineProps({
      iconClass: {
        type: String,
        required: true,
      },
      className: {
        type: String,
        default: "",
      },
      color: {
        type: String,
        default: "",
      },
    });
    
    const iconName = computed(() => `#icon-${props.iconClass}`);
    const svgClass = computed(() => {
      if (props.className) {
        return `svg-icon ${props.className}`;
      }
      return "svg-icon";
    });
    </script>
    
    <style scope lang="scss">
    .sub-el-icon,
    .nav-icon {
      display: inline-block;
      font-size: 15px;
      margin-right: 12px;
      position: relative;
    }
    
    .svg-icon {
      width: 1em;
      height: 1em;
      position: relative;
      fill: currentColor;
      vertical-align: -2px;
    }
    </style>
    
  5. main.ts中註冊為全局組件

    import svgIcon from "./components/SvgIcon/index.vue";
    
    app.component("svg-icon", svgIcon);
    

使用#

<template>
  <div style="display: flex; gap: 20px">
    <svg-icon iconClass="Github"></svg-icon>
    <svg-icon iconClass="Aiming"></svg-icon>
  </div>
</template>

<script setup lang="ts">

</script>

<style lang="scss" scoped>

</style>

效果#

image-20230711200625128

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。