Vue插槽的那些事兒

2.4 插槽

1. 插槽內容

插槽可以包含任意的模板代碼,包括html,甚至其他組件。
如下:<slot></slot> 在渲染時將被替換成組件<text-document> 之間的所有內容

在這裏插入圖片描述

完整代碼

2. 編譯作用域

插槽裏插入的內容能訪問的作用域
例如下面的 doc.title 就是在訪問同級作用域裏的內容
在這裏插入圖片描述
完整代碼

3. 插槽設置默認內容

如果插槽裏沒有提供內容,可以設置默認渲染的內容:如下
在這裏插入圖片描述
完整代碼

4. 具名插槽

涉及多個插槽時,我們用name的屬性來區分各個插槽,沒有name屬性的默認name屬性值爲 default,如下:
在這裏插入圖片描述
完整代碼

5. 作用域插槽

插槽內如何訪問別的作用域下的內容?
如下,要在裏用user.firstName來替換默認的user.lastName值,如何在裏訪問到user呢?vue提供了一套方案,如下:
完整代碼鏈接
在這裏插入圖片描述

單個插槽時的縮寫語法和解構賦值語法

// 【原來寫法】
<current-user>
  <template v-slot:default="slotProps">
			{{ slotProps.user.firstName }}
  </template>
 </current-user>

// 【縮寫語法】
 <current-user v-slot="slotProps">
        {{ slotProps.user.firstName }}
 </current-user>

// 【也可用ES5的解構賦值語法】
 <current-user v-slot="{ user }">
        {{ user.firstName }}
 </current-user>

6. Dynamic Slot Names

插槽名可以是動態的

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

7. 具名插槽的縮寫

用#代替v-slot:

<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>

更多Vue文檔解讀:《Vue Doc 筆記》

(完)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章