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

99封情书 提交于 2019-12-17 19:13:27

问题


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>

回答1:


You need to use a scoped slot. You were almost there, I just added the template that creates the scope.

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

Here is your code updated.

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>
    <template slot-scope="{signal}">
      <my-child :signal="signal"></my-child>
      <my-child :signal="signal"></my-child>
    </template>
  </my-parent>
</div>

The release of Vue 2.6 introduces a unified v-slot directive which can be used for normal or scoped slots. In this case, since you're using the default, unnamed slot, the signal property 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>


来源:https://stackoverflow.com/questions/45180114/how-to-pass-props-using-slots-from-parent-to-child-vuejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!