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

新手上路,请多包涵

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

我注册了以下组件:

 <template id="goal">
  <h1>Goal:{{data.text}}</h1>
</template>

而不是像这样加载它

<goal></goal>

我想从一个变量名加载,像这样:

 <{{mytemplate.type}}></{{mytemplate.type}}>

当然,在这种情况下,mytemplate.type 等于“目标”

原文由 sigmaxf 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 572
2 个回答

使用这样的 动态组件

 <component :is="myTemplate.type"></component>

原文由 thanksd 发布,翻译遵循 CC BY-SA 4.0 许可协议

我遇到了同样的问题,因为我使用的是 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>

原文由 Rakshit Arora 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题