Search code examples
javascriptvue.jsvuejs3vue-composition-apivue-script-setup

Can I import a component in Vue.js with path based on prop?


I am using the Material design Icons library for Vue.js. This library contains a folder and every icon is a single file component in that folder.

I have another component, ToolbarButton, that has a prop Icon and I want to import component with name same as the passed prop.

Here's my code:

<template>
    <button>
        <MyIcon></MyIcon>
    </button>
</template>

<script>

import MyIcon from `icons/${icon}.vue`
export default {
    name: 'ToolbarButton',
    props: ['icon']
    components: {
        MyIcon
    }
}
</script>

This code throws an error Parsing error: Unexpected token ` Using 'icons/' + icon + '.vue' doesn't help. Is there any way to do that? I have been searching for over an hour but didn't find any solution. Somebody recommended importing all of the components because the unused ones will go away when compiling, but that doesn't sound like the right way to do that.


Solution

  • You can use async components as follows :

    <template>
      <MyIcon />
    </template>
    
    <script setup>
    import { defineAsyncComponent } from "vue";
    
    const props = defineProps(["icon"]);
    const MyIcon = defineAsyncComponent(function () {
      return import(`./icons/Icon${props.icon}.vue`);
    });
    </script>