簡體   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