Search code examples
javascripttypescriptvue.jspolymorphismstrategy-pattern

How to implement a strategy pattern for Vue components


So here's the thing. I have a Cat, Dog and Horse which all implement the Animal interface. For each of these I have a DogComponent, CatComponent and HorseComponent.

Question:

How do I create an AnimalComponent component that takes any Animal but renders DogComponent in the case it's a Dog without using switch-case or a bunch of v-ifs in the <template>?

Please assume that just rendering a different imageUrl and title is not enough.


Solution

  • Just use Vue dynamic component :)

    This special component renders a component given the name provided in the is property.

    <template>
      <component v-for="animal in animals" :is="`${animal.type}-component`"/>
    </template>
    
    <script>
    // vue syntax omitted for simplicity
    animals: [
      { type: 'dog' },
      { type: 'cat' },
    ]
    </script>