[TOC]
# `v-slot`(插槽)
父頁面在組件標簽內插入任意內容,子組件內插糟 slot 控制擺放位置(匿名插槽、具名插槽)
**插槽分類**
插槽一共就三大類
1. 匿名插槽 (也叫默認插槽): 沒有命名,有且只有一個
2. 具名插槽:相對匿名插槽組件 slot 標簽帶 name 命名的
3. 作用域插槽:子組件內數據可以被父頁面拿到 (解決了數據只能從父頁面傳遞給子組件)
# 具名插槽
子組件:
```
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot> // 匿名插槽
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
```
如果不在子組件中使用插槽(slot),那么在子組件中寫任何代碼都是無效的的,不會顯示。
父級模板里的所有內容都是在父級作用域中編譯的;子模板里的所有內容都是在子作用域中編譯的。
# 作用域插槽
下面代碼中的`slotProps`(可以隨意命名)可以讀取子組件上所有的屬性數據集合。
父頁面:
```
<todo-list>
<template v-slot:todo="slotProps" > // slotProps 接取的是子組件標簽slot上屬性數據的集合所有v-bind:user="user"
{{slotProps.user.firstName}}
</template>
</todo-list>
```
子組件:
```
<slot name="todo" :user="user" :test="test">
{{ user.lastName }} // {{ user.lastName }}是默認數據 v-slot:todo 當父頁面沒有 (="slotProps") 時顯示 Zhang
</slot>
data() {
return {
user:{
lastName:"Zhang",
firstName:"yue"
},
test:[1,2,3,4]
}
}
...
```
可以看出頁面最終渲染為: yue
# 總結
用`v-slot`,需要考慮好:
1. 是否需要命名 (匿名插槽,具名插槽)
2. 父頁面是否需要取存在子頁面的數據 (作用域插槽)
# 參考
> [詳解 vue2.6 插槽更新 v-slot 用法總結](https://www.jb51.net/article/157565.htm)
> [#插槽](https://vue3js.cn/docs/zh/guide/component-slots.html#插槽)
- Introduction
- Introduction to Vue
- Vue First App
- DevTools
- Configuring VS Code for Vue Development
- Components
- Single File Components
- Templates
- Styling components using CSS
- Directives
- Events
- Methods vs Watchers vs Computed Properties
- Props
- Slots
- Vue CLI
- 兼容IE
- Vue Router
- Vuex
- 組件設計
- 組件之間的通信
- 預渲染技術
- Vue 中的動畫
- FLIP
- lottie
- Unit test
- Vue3 新特性
- Composition API
- Reactivity
- 使用 typescript
- 知識點
- 附錄
- 問題
- 源碼解析
- 資源