繁体   English   中英

如何为 Vue 组件实现策略模式

[英]How to implement a strategy pattern for Vue components

事情就是这样。 我有一个CatDogHorse ,它们都实现了Animal接口。 对于其中的每一个,我都有一个DogComponentCatComponentHorseComponent

问题:

如何创建一个AnimalComponent组件,它接受任何Animal但在它是Dog的情况下呈现DogComponent而不使用switch-case<template>中的一堆v-if

请假设仅渲染不同的imageUrltitle是不够的。

只需使用Vue 动态组件:)

这个特殊的组件根据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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM