如何为 Vue 组件实现策略模式
How to implement a strategy pattern for Vue components
事情是这样的。我有一个 Cat
、Dog
和 Horse
,它们都实现了 Animal
接口。对于其中的每一个,我都有一个 DogComponent
、CatComponent
和 HorseComponent
.
问题:
我如何创建一个 AnimalComponent
组件,它接受任何 Animal
但在不使用 switch-case
或 Dog
的情况下渲染 DogComponent
<template>
?
中的一堆 v-if
请假设仅仅渲染不同的 imageUrl
和 title
是不够的。
只需使用 Vue dynamic component :)
此特殊组件根据 is
属性 中提供的名称呈现组件。
<template>
<component v-for="animal in animals" :is="`${animal.type}-component`"/>
</template>
<script>
// vue syntax omitted for simplicity
animals: [
{ type: 'dog' },
{ type: 'cat' },
]
</script>
事情是这样的。我有一个 Cat
、Dog
和 Horse
,它们都实现了 Animal
接口。对于其中的每一个,我都有一个 DogComponent
、CatComponent
和 HorseComponent
.
问题:
我如何创建一个 AnimalComponent
组件,它接受任何 Animal
但在不使用 switch-case
或 Dog
的情况下渲染 DogComponent
<template>
?
v-if
请假设仅仅渲染不同的 imageUrl
和 title
是不够的。
只需使用 Vue dynamic component :)
此特殊组件根据 is
属性 中提供的名称呈现组件。
<template>
<component v-for="animal in animals" :is="`${animal.type}-component`"/>
</template>
<script>
// vue syntax omitted for simplicity
animals: [
{ type: 'dog' },
{ type: 'cat' },
]
</script>