Vue3之插槽

含義

簡(jiǎn)而言之,就是父組件提供的插槽內(nèi)容(Click me)替換插槽出口(slot)


插槽示意圖

默認(rèn)插槽

// FancyButton.vue
<button type="submit">
  <!-- 插槽出口 -->
  <slot>
    Submit <!-- 默認(rèn)內(nèi)容:如果沒有插槽內(nèi)容Click me!,會(huì)渲染默認(rèn)類容Submit -->
  </slot>
</button>
// 父組件使用
<FancyButton>
  Click me! <!-- 插槽內(nèi)容 -->
</FancyButton>

具名插槽

// 父組件使用
<BaseLayout>
  // v-slot:header的簡(jiǎn)寫形式就是#header
  <template #header>
    <h1>Here might be a page title</h1>
  </template>
  // 默認(rèn)插槽,#default不寫也可以,會(huì)往沒有name的slot插槽替換
  <template #default>
    <p>A paragraph for the main content.</p>
    <p>And another one.</p>
  </template>

  <template #footer>
    <p>Here's some contact info</p>
  </template>
</BaseLayout>

// BaseLayout.vue
<div class="container">
  <header>
    <slot name="header"></slot>
  </header>
  <main>
    <slot></slot>
  </main>
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>
具名插槽示意圖

動(dòng)態(tài)插槽

// dynamicSlotName可以是一個(gè)變量,動(dòng)態(tài)的名稱
<base-layout>
  <template v-slot:[dynamicSlotName]>
    ...
  </template>

  <!-- 縮寫為 -->
  <template #[dynamicSlotName]>
    ...
  </template>
</base-layout>

作用域插槽

插槽的內(nèi)容無法訪問到子組件的狀態(tài),如果需要訪問子組件的數(shù)據(jù)就需要使用作用域插槽了。

<!-- <MyComponent> 的模板 -->
<div>
  <slot :text="greetingMessage" :count="1"></slot>
</div>

<MyComponent v-slot="slotProps">
  {{ slotProps.text }} {{ slotProps.count }}
</MyComponent>
// 也可以使用解構(gòu)的方式
<MyComponent v-slot="{text, count}">
  {{ text }} {{ count }}
</MyComponent>
作用域插槽示意圖
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容