在Vue 3中将组件用作对象属性

huangapple go评论67阅读模式
英文:

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 &#39;vue&#39;

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?

&lt;div v-for=&quot;route in routes&quot;&gt;
{{ route.icon }} // not working.
&lt;/div&gt;

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:

&lt;template&gt;
  &lt;component :is=&quot;route.icon&quot; /&gt;
&lt;/template&gt;

&lt;script setup&gt;
import Header from &#39;./Header.vue&#39;

const globalComponentName = &#39;MyPopup&#39;

const route = reactive({
  icon: &#39;MyPopup&#39;,
  // or
  icon: Header
})
&lt;/script&gt;

huangapple
  • 本文由 发表于 2023年2月6日 19:55:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75360991.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定