Dave Draper
Dave Draper

Reputation: 1845

Cannot pass properties to a component in a slot in vue.js?

I'm trying to use Vue.js (v2.1.3) to create nested components but I can't figure out how to bind data between them.

This JSFiddle demonstrates what I'm trying to achieve.

HTML...

 <div id="test">
   <comp1>
     <comp2 :message="message"></comp2>
   </comp1>
 </div>

JS...

    var template = `<div>
      <comp2 :message="message"></comp2>
      <slot :message="message"></slot>
    </div>`;

    Vue.component("comp1", {
      template: template,
      data: function() {
        return {
          message: "Hello"
        };
      }
    });

    var template2 = `<div>
       <span>Message is: {{ message }}</span>
    </div>`;

    Vue.component("comp2", {
      template: template2,
      props: ["message"]
    });

    new Vue({
      el: "#test"
    });

If I declare the child component directly in the template of the parent component then the data is passed correctly. But when the child component is assigned to a slot in the parent component then the data is not passed.

I've read and re-read the documentation but can't figure out whether what I want to do is possible and if so, what it is that I'm doing wrong.

Any help resolving this would be greatly appreciated!

Upvotes: 2

Views: 2287

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 219936

To use scoped slots, wrap your parent's content in a template tag with a scope attribute:

<comp1>
  <template scope="{ message }">
    <comp2 :message="message"></comp2>
  </template>    
</comp1>

Here's your updated fiddle: https://jsfiddle.net/Lbz6Ly4a/1/

Upvotes: 3

Related Questions