How to pass props using slots from parent to child -vuejs

Viewed 60571

I have a parent component and a child component.

The parent component's template uses a slot so that one or more child components can be contained inside the parent.

The child component contains a prop called 'signal'.

I would like to be able to change data called 'parentVal' in the parent component so that the children's signal prop is updated with the parent's value.

This seems like it should be something simple, but I cannot figure out how to do this using slots: Here is a running example below:

const MyParent = Vue.component('my-parent', {
  template: `<div>
               <h3>Parent's Children:</h3>
               <slot :signal="parentVal"></slot>
             </div>`,

  data: function() {
    return {
      parentVal: 'value of parent'
    }
  }
});

const MyChild = Vue.component('my-child', {
  template: '<h3>Showing child {{signal}}</h3>',
  props: ['signal']
});

new Vue({
  el: '#app',
  components: {
    MyParent,
    MyChild
  }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <my-parent>
    <my-child></my-child>
    <my-child></my-child>
  </my-parent>
</div>

3 Answers

You may try this technique.

In this example. Let assume a parent component wants to share prop foo with value bar.

Parent component

<parent>
    <template v-slot:default="slotProps">
        // You can access props as object slotObjects {foo"bar"}
        <p>{{slotProps.foo}}</p>
    </template>
<parent>

Child

<template>
    <div class="parent">
        <slot :foo="bar" />
    </div>
</template>

Got the idea from this video

I hope it helped you accomplish your tasks.

I added this code inside of <v-data-table></v-data-table>

<template
  v-for="slot in slots"
  v-slot:[`item.${slot}`]="{ item }"
>
  <slot
    :name="slot"
    :item="item"
  />
</template>

And I added a props called slots. When I call the component I send a slots like:

<my-custom-table-component :slots="['name']">

 <template v-slot:name="{ item }">
  {{ item.first_name + item.last_name}}
 </template>

</my-custom-table-component>
Related