简体   繁体   中英

Dynamic import in JS and Vue.js

I am writing a web application using the Vue.js framework. There was a need to use dynamic import. You need to import using the parameter with its name, and then define the resulting component.

The syntax for the following dynamic import in js:

async () => {
    const module_path = 'module_path';
    const module = await import(module_path)
    module.default();
  }

Thus, using a dynamically imported library is only possible inside an asynchronous function. I need to use the imported component elsewhere:

<template>
   <div>
      <!-- imported component definition -->
      <component v-bind:is="my_component"></component>
   </div>
</template>

<script lang="coffee">
   # Here you need to dynamically import the component, so that you 
   # can define it later on line 3.
   # How to make a static import is clear (shown below). But I need a 
   # dynamic one.
   import my_component from "./component_title.Vue"
   
   export default {
      props: () -> {
         # The name of the component to be imported.
         # Transferred from another component.
         component_title: {type: String, default: null}
      }

      components: {
         # The component is declared
         my_component: my_component
      }
   }
</script>

Is it possible to implement dynamic import in this task?

Yea. Just use import() at your component:

components: {
   my_component: () => import(path)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM