Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variables through <slot> to parent component

Child component:

Vue.component('v-data', {

  template: `
    <div class="v-data">
      <slot :visible-data="visibleData"></slot>
    </div>
  `,    

  computed: {

    visibleData(){
      return [1,2,3];
    },

  },

});

In parent component I am using it like this:

<v-data>
   <li v-for="x in visibleData">{{x}}</li>
</v-data>

but visibleData is not passed in the template. I should be able to get 1,2,3.

Is there a way to pass variables between components like this?

like image 258
Alex Avatar asked Oct 22 '25 12:10

Alex


1 Answers

You are definitely looking for Scoped Slots. With this, one can easily pass data from the child component to the parent such that data could be referred to in the template being passed on to the child component. You can use it to pass data from your child component as

<div class="v-data">
    <slot :visible-data="visibleData"></slot>
</div>

Which can be referred in the parent as

<v-data>
  <template #default="{visibleData}">
    <li v-for="(value, index) in visibleData" :key="index">{{value}}</li>
  </template>
</v-data>

Few things to note here

  1. The properties can be referred to using the name of the slot. Here we are referring to the default slot thus using the keyword default.

  2. We can use Object Destructuring to directly access the property passed to the parent component

Sanbox present HERE

like image 186
Saksham Avatar answered Oct 25 '25 02:10

Saksham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!