Vue slot 跨组件传递

很多情况下,我们需要使用到嵌套组件,嵌套组件中深层的组件如何获取外部传进来的 slot 呢?

比如我们有一个三层嵌套组件

<grandfather>
  <parent>
    <child></child>
  </parent>
</grandfather>
// child 组件
<slot name="child" :childData="obj">
  <view class="item-menu-name">{
   
   {obj.name}}</view>
</slot>

当你在 grandfather  传VNode给 child 组件时,该怎么办呢

嵌套传递

1. 首选在 grandfather 组件正常写你需要传给 child 组件的VNode,如下:

<template v-slot:child="{ childData }">
  <view>{
   
   { childData.sex }}</view>
</template>

2. 在 parent  传递 VNodeslot  

<child>
  <template v-slot:child="{childData}">
    <slot name="child" :childData="childData" />
  </template>
</child>

结束,完成了。缺点就是如果层级太深太麻烦,不过一般情况可以使用

猜你喜欢

转载自blog.csdn.net/qq_41887214/article/details/121343604