Vue 3 importiert dynamisch basierend auf Requisiten
P粉388945432
P粉388945432 2023-11-16 11:40:01
0
1
768

Ich verwende Unplugin-Icon, um eine Icon-Komponente zu erstellen, normalerweise kann ich z.B.

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

Es funktioniert, aber wenn wir ein anderes Symbol verwenden möchten, ist es unpraktisch, es einzeln zu importieren. Deshalb habe ich eine dynamische Komponente namens Eunoicon.vue erstellt

<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>

Aber wenn ich versuche, es in eine Komponente zu importieren, wird ein Fehler ausgegeben Uncaught (in Promise) TypeError: 无法解析模块说明符 '~icons/prime/copy'. Irgendwelche Vorschläge für diesen Ansatz oder eine Symbolbibliothek, die einen einfachen Ansatz bietet? Ich habe Vue Font Awesome ausprobiert, aber es ist immer noch nicht so einfach, wie ich es möchte.

P粉388945432
P粉388945432

Antworte allen(1)
P粉396248578

不幸的是,目前无法动态创建导入。几个月前我发现自己遇到了同样的问题。我的解决方案是将图标视为 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 图标,请毫不犹豫地受到启发、修改它或使用它

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!