Angel D.
Angel D.

Reputation: 225

how to pass components as props in vue js and how to use it properly?

Hello I have a Child component that the main function is to filter and render a list of items. This child component is to be used in multiple parent components(views) and depending on the parent component the child component need to render a different child component (grand child).

Parent Component

    <template>
     <main>
    //Child Component
    <list-component
      name="my items"
      //List of Items I need to render
      :list="items.list"
    >
      //Slot Passing my grandchild component
      <template slot="child-component">
        <component :is="child_component" :items="item"></component>
      </template>
    </list-component>
  </main>
</template> 

    <script>
    import ListComponent from '.ListComponent';
    import ItemComponent from '.ItemComponent.vue';

export default {
  components: {
    ListComponent,
    ItemComponent
  },

  data() {
    return {
      child_component: 'ItemComponent'
    };
  },
}
</script>

ListComponent.vue (child component)

<template>
  <main>
    <v-row class="ma-0">
      <v-col v-for="(item, index) in list" :key="index" class="pa-0">
        // I would like render my grandchild component here. 
        <slot name="child-component"></slot>
      </v-col>
    </v-row>
  </main>
</template>

<script>

export default {
  props: {
    name: {
      type: String,
      required: true
    },

    list: {
      type: Array,
      required: true
    }
  }
};
</script>

ItemComponent.vue (grand child)

<template>
  <div>
    <v-img
      src="item.image"
    ></v-img>

    <v-row>
      <span>{{
        item.name
      }}</span>
    </v-row>
  </div>
</template>

<script>
export default {
  props: {
    item: {
      type: Object,
      required: true
    }
  }
}
</script>

So basically I need to be able to pass ItemComponent.vue(grandchild) from the View(grandfather) to the View's ListComponent.vue(child) so that the child component can loop trough the items passed from the parent and use the grand child to render the information.

Also where do I declare the props for the grandchild?

Upvotes: 6

Views: 6744

Answers (1)

Angel D.
Angel D.

Reputation: 225

I was able to find a solution after all I will leave this for those who need it.

basically in the child component we need to give access to the attribute to the parent trough the slot by binding the item like:

<slot name="child-component" :item="item"></slot>

and on the parent we can access it by binding the slot and giving a name to the object in this case I chose child and notice that on the component we can access item by declaring child.item

  <template v-slot:child-component="child">
    <component :is="child_component" :itinerary="child.item"></component>
  </template>

Upvotes: 11

Related Questions