Search code examples
javascriptvue.jsvuejs2vue-componentinversion-of-control

vue.js: How to specify which child component to use?


In my app there are generic and brand specific components. Let's say I have 2 brand specific components Product_brand_A.vue and Product_brand_B.vue, which I would like to display in a list. The parent component ProductList.vue is generic (used for both brands).

What are my options in ProductList.vue to specify which child component to use?

// ProductList.vue (generic)
import Product from 'Product.vue' // importing won't do
var ProductList = {
  components: {
    Product
  },
...
}

I don't want to import both child components and decide at run time, it should be a build time solution.


Solution

  • I think that it's better to use slots api here. Here's example of usage of the list component:

    <ProductList :items="someProductsBrandA">
        <template v-slot:item="props">
            <Product_brand_A product="props.product">
            </Product_brand_B>
        </template>
    </ProductList>
    

    This way you can add as much different product components as you want in the future. You can check the slot API here: https://v2.vuejs.org/v2/guide/components-slots.html