Vue 3 dynamically imports based on Props
P粉388945432
P粉388945432 2023-11-16 11:40:01
0
1
709

I am using unplugin-icon to create an icon component, normally I can import e.g.

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

It works, but if we want to use another icon, it feels inconvenient to import one by one, so I created a dynamic component called Eunoicon.vue

 

But when I try to import it into the component, it throws the errorUncaught (in Promise) TypeError: Unable to resolve module specifier '~icons/prime/copy'.Any suggestions for this approach or any icon library that provides a simple approach? I've tried vue font Awesome but it's still not as simple as I'd like.

P粉388945432
P粉388945432

reply all (1)
P粉396248578

Unfortunately, it is currently not possible to create imports dynamically. I found myself with the same problem a few months ago. My solution was to treat the icons as SVG and create an import file attached to my project like this:

interface SvgObject { [key: string]: Function; } export function importSvg(icon: string) { const svg = { "sliders-horizontal": () => { return '      '; }, }

And create a view component as shown below, which will retrieve the icon corresponding to the given name with the help of props.

  

Of course, manually creating the import file would be cumbersome, so in my case I created a python script that takes the path to the SVG icons folder and processes each icon to shrink them and create the import file automatically. This script works with icons from the Phosphor Icon Library. You can find the code for the scripts and Vue components in the github repository:

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

If you decide to use the Phosphor icon, don't hesitate to be inspired by it, modify it, or use it

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!