學習筆記:Vue——插槽


關於Vue插槽,只用過最簡單的語法,現在完整地走一遍官方文檔說明,並且探索更多用法。


 

 

01.如果組件中沒有包含一個<slot>元素,則該組件起始標簽和結束標簽之間的任何內容都會被拋棄。

02.父級模板里的所有內容都是在父級作用域中編譯的;子模板里的所有內容都是在子作用域中編譯的。

03.后備(默認)內容

<button type="submit">
  <slot>Submit</slot>
</button>

04.具名插槽

<slot>元素有一個特殊的特性:name

<div class="container">
  <header>
    <slot name="header"></slot>
  </header>
  <main>
    <slot></slot>
  </main>
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>

一個不帶name的<slot>出口會帶有隱含的名字"default"

 

05.作用域插槽

讓插槽內容能夠訪問子組件中才有的數據是很有用的。

綁定在<slot>元素上的特性被稱為插槽prop

<current-user>
  <template v-slot:default="slotProps">
    {{ slotProps.user.firstName }}
  </template>
</current-user>

獨占默認插槽的縮寫語法

<current-user v-slot="slotProps">
  {{ slotProps.user.firstName }}
</current-user>

只要出現多個插槽,請始終為所有的插槽使用完整的基於<template>的語法

<current-user>
  <template v-slot:default="slotProps">
    {{ slotProps.user.firstName }}
  </template>

  <template v-slot:other="otherSlotProps">
    ...
  </template>
</current-user>

 

06.解構插槽Prop

<current-user v-slot="{ user }">
  {{ user.firstName }}
</current-user>
<current-user v-slot="{ user: person }">
  {{ person.firstName }}
</current-user>
<current-user v-slot="{ user = { firstName: 'Guest' } }">
  {{ user.firstName }}
</current-user>

 

07.動態插槽名

<base-layout>
  <template v-slot:[dynamicSlotName]>
    ...
  </template>
</base-layout>

 

08.具名插槽的縮寫#

<base-layout>
  <template #header>
    <h1>Here might be a page title</h1>
  </template>

  <p>A paragraph for the main content.</p>
  <p>And another one.</p>

  <template #footer>
    <p>Here's some contact info</p>
  </template>
</base-layout>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM