如何从Vue.js中的变量名加载组件?

rap*_*dko 9 javascript vue.js

我想在我的vue.js应用程序中从动态变量名加载一个组件.

我注册了以下组件:

<template id="goal">
  <h1>Goal:{{data.text}}</h1>
</template>
Run Code Online (Sandbox Code Playgroud)

而不是像这样加载它

<goal></goal>
Run Code Online (Sandbox Code Playgroud)

我想从变量名加载,如下所示:

<{{mytemplate.type}}></{{mytemplate.type}}>
Run Code Online (Sandbox Code Playgroud)

当然,mytemplate.type会在哪里,在这种情况下等于"目标"

Rak*_*ora 17

我遇到了同样的问题,因为我使用的是 Vue 3。经过一番研究,我发现 Vue 3 中定义动态组件(异步组件)的过程有点不同。我希望这段代码对某人有所帮助。

<template>
    <component :is="comp"></component>
</template>

<script>
//Vue 3 is having a special function to define these async functions
import {defineAsyncComponent} from "vue";

export default {
 name: "DynamicComponent",
 //I am passing the name of the Component as a prop
 props: {
     componentName:{
         type: String,
         required: true
     }
 },
 computed: {
  comp () {
      return defineAsyncComponent(() => import(`../components/${this.componentName}.vue`))
  }
}
}
</script>
Run Code Online (Sandbox Code Playgroud)


tha*_*ksd 15

使用这样的动态组件:

<component :is="myTemplate.type"></component>
Run Code Online (Sandbox Code Playgroud)