Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

vue.js - How to pass props using slots from parent to child -vuejs

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...