首頁  >  問答  >  主體

Vue 3 基於 Props 動態導入

我正在使用 unplugin-icon 建立圖示元件,通常情況下我可以導入例如

//script
import IconCopy from '~icons/prime/copy'
//template
<IconCopy/>

它可以工作,但是如果我們想使用另一個圖標,那麼逐個導入感覺不方便,所以我創建了一個名為 Eunoicon.vue 的動態元件

<script setup>
const props = defineProps({
    icon : {type:String}
})
const from = `~icons/prime/${props.icon}`
const TheIcon = await import(/* @vite-ignore */from)
console.log('ti',TheIcon)
</script>
<template>
<TheIcon/>  
</template>

但是當我嘗試將其導入到元件時,它會拋出錯誤 Uncaught (in Promise) TypeError: 無法解析模組說明符 '~icons/prime/copy'. 對於這種方法或任何提供簡單方法的圖標庫有什麼建議嗎?我已經嘗試過 vue font Awesome 但仍然沒有我想要的那麼簡單。

P粉388945432P粉388945432337 天前810

全部回覆(1)我來回復

  • P粉396248578

    P粉3962485782023-11-17 10:34:12

    不幸的是,目前無法動態建立導入。幾個月前我發現自己遇到了同樣的問題。我的解決方案是將圖標視為 SVG 並創建一個附加到我的專案的導入文件,如下所示:

    interface SvgObject {
      [key: string]: Function;
    }
    
    export function importSvg(icon: string) {
      const svg = {
        "sliders-horizontal": () => {
          return '<line x1="148" y1="172" x2="40" y2="172" fill="none" /> <line x1="216" y1="172" x2="188" y2="172" fill="none" /> <circle cx="168" cy="172" r="20" fill="none" /> <line x1="84" y1="84" x2="40" y2="84" fill="none" /> <line x1="216" y1="84" x2="124" y2="84" fill="none" /> <circle cx="104" cy="84" r="20" fill="none" /> ';
        },
    }
    

    並建立一個視圖元件,如下所示,借助道具,該元件將檢索與給定名稱相對應的圖示。

    <script setup lang="ts">
    import { computed } from "vue";
    import { importSvg } from "@/icons/importSvg";
    
    interface Props {
      icon: string;
    }
    
    const IconComponent = importSvg(props.icon);
    
    </script>
    
    <template>
      <span>
        <svg
          xmlns="http://www.w3.org/2000/svg"
          viewBox="0 0 256 256"
          :aria-labelledby="icon"
          v-html="IconComponent"
        ></svg>
      </span>
    </template>
    
    <style>
    ...
    </style>
    
    <MyIcon icon="sliders-horizontal"/>
    

    當然,手動建立匯入檔案會很麻煩,因此在我的例子中,我建立了一個 python 腳本,該腳本採用 SVG 圖示資料夾的路徑並處理每個圖示以縮小它們並自動建立匯入檔案。 此腳本適用於螢光粉圖示庫中的圖示。 您可以在 github 儲存庫中找到腳本和 Vue 元件的程式碼:

    https://github.com/fchancel/Phosphor-icon-vue-component

    如果您決定使用 Phosphor 圖標,請毫不猶豫地受到啟發、修改它或使用它

    回覆
    0
  • 取消回覆