英文:
Using a component as an object property in Vue 3
问题
我想知道在Vue 3中是否有一种方法可以将一个组件用作属性。
以下面的TS接口为例:
```vue
import type { Component } from 'vue'
interface Route {
url: string
icon: Component
name: string
}
我可以在模板中使用基于该接口的对象来渲染一个组件吗?
<div v-for="route in routes">
{{ route.icon }} // 不起作用。
</div>
任何帮助将不胜感激。谢谢!
<details>
<summary>英文:</summary>
I was wondering if there was a way to use a Component as a property in Vue 3.
Take for example the below TS interface:
```vue
import type { Component } from 'vue'
interface Route {
url: string
icon: Component
name: string
}
Can I use an object based on said interface in a template to render a Component like this?
<div v-for="route in routes">
{{ route.icon }} // not working.
</div>
Any help would be much appreciated. Thanks!
答案1
得分: 1
你想要使用动态组件。
它是一个特殊的组件,接受已注册组件的名称或整个导入的组件对象作为 prop:
<template>
<component :is="route.icon" />
</template>
<script setup>
import Header from './Header.vue';
const globalComponentName = 'MyPopup';
const route = reactive({
icon: 'MyPopup',
// 或者
icon: Header
})
</script>
英文:
You want to use dynamic components.
It's a special component that take a registered component's name or an entire imported component object as a prop:
<template>
<component :is="route.icon" />
</template>
<script setup>
import Header from './Header.vue'
const globalComponentName = 'MyPopup'
const route = reactive({
icon: 'MyPopup',
// or
icon: Header
})
</script>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论