關於vue slot 的多級傳遞使用

關於slot 以及scope-slot的基本使用,官方文檔已經有了詳細的介紹:點擊這裏查看,這裏就不復述了。

但是在實際的使用過程中,常常會出現外部組件內容需要多級嵌套傳遞到目標組件,那麼slot可以如何實現呢?
現在假設有A,B,C三個組件,層級關係為A>B>C(爺爺,父親,兒子)

C:

<div>
    C組件
    <div>
      <slot name="pane" :data="我是C">我是c組件(兒子)---外部沒傳遞,我才顯示</slot>
    </div>
</div>

B:

<div>
    B組件---這是一箇中間傳遞的slot
    <C>
        <div slot="pane" slot-scope="{data}">
          <slot name="pane" :data="data"></slot>
        </div>
    </C>
</div>

A:

<div>
    A組件
    <B>
    <div slot="pane" slot-scope="{data}">
      {{data}}注意,我要傳到C了
    </div>
    </B>
</div>

其他擴展用法跟此類似

 

 

Vue3 slot插槽多層傳遞

如果你想傳遞一個slot,從爺到孫的傳遞, 看了網上的一些方案,依賴注入都來了,其實沒那麼麻煩

直接上代碼

最頂層組件,插入一個按鈕到 slot name為 btn的 插槽裏面,Button接收一個row的參數,參數可能有多個,這裏 用了 { row } 只取 row

<topComponent>
    <template #btn="{ row }">
        <Button :row="row"/>
    </template>
</topComponent>

在中間組件,這裏把插入一個 插槽 插入到 slot name為 btn的 插槽裏面,它接收一個 row的參數, 從 v-slot:btn / #btn 裏面來的

slot的參數傳遞是從下往上的,通過 #btn=“xxx” xxx來接收

<middleComponent>
    <template #btn="row">
         <slot name="btn" :row="row"></slot>
    </template>
</middleComponent>

最底層組件,僅有一個插槽,向上傳遞 item的值 為 row的參數。

<bottomComponent>
    <slot name="btn" :row="item"></slot>
</bottomComponent>

以上。
從頂層組件插入的Button組件,就能獲取到最底層組件傳遞過來的值,Vue3本身就支持這種 slot 跨層傳遞,不需要那些額外的騷操作 XD

 

<topComponent><template #btn="{ row }"><Button :row="row"/></template></topComponent>