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

I have a parent component and a child component.

The parent component template uses a slot, so one or more child components can be contained within the parent.

The child component contains a props called "signal".

I would like to be able to change the data named parentVal in the parent component so that the parent value is updated in the child signal sub.

It looks like it should be something simple, but I can't figure out how to do it using slots: Here's a working example below:

const MyParent = Vue.component('my-parent', {
  template: '<div>
               <h3>Parent 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>
      

Run codeHide result


+7


source to share


1 answer


You need to use a limited slot . You were almost there, I just added a template that creates a region.

  <my-parent>
    <template slot-scope="{signal}">
      <my-child :signal="signal"></my-child>
      <my-child :signal="signal"></my-child>
    </template>
  </my-parent>

      

Here's your code updated.



const MyParent = Vue.component('my-parent', {
  template: '<div>
               <h3>Parent 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>
    <template slot-scope="{signal}">
      <my-child :signal="signal"></my-child>
      <my-child :signal="signal"></my-child>
    </template>
  </my-parent>
</div>
      

Run codeHide result



The Vue 2.6 release introduced a unified directive v-slot

that can be used for regular or constrained slots. In this case, since you are using the default slot, the unnamed slot, the property signal

can be accessed via v-slot="{ signal }"

:

  <my-parent>
    <template v-slot="{ signal }">
      <my-child :signal="signal"></my-child>
      <my-child :signal="signal"></my-child>
    </template>
  </my-parent>

      

+8


source







All Articles