简体   繁体   中英

Access method or property from parent within a non named slot in vuejs component

I'm using Vue 2.4.1

And I'm trying to reproduce what is shown there : link to alligator.io

Which is basycally accessing a non-named slot data.

//Chid Component
<template>
    <slot :test="myTest"></slot>
</template>

data(){
    return {
       myTest: "I should be getable"
    }
}

//Parent
<template>
    <child-component>
        <template scope="defaultSlotScope">
            {{defaultSlotScope.test}}
        </template>
    </child-component>
</template>

So this is the first time I see the mension of scope="defaultSlotScope" Is this the right way? However I don't find how to properly make this work.

You need to wrap the slot in your child component which is missing in the parent;

<template>
  <child-component>
    <template scope="defaultSlotScope">
       {{defaultSlotScope.test}}
    </template>
  </child-component>
</template>

Also in the child component, you should not expose slot directly in the template root. Wrap it in another tag; The reason behind this is that the root template can accept only one element while a slot can be multiple:

<template>
  <div>
    <slot :test="myTest"></slot>
  </div>
</template>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM