一直模糊所以梳理一下,看了好多篇園友的文章和官網文檔在這整理一下
默認插槽
//slot組件
<template> <div class="slots"> slot的用法 <SlotChild> <div class="no-name">我是嵌在子組件內不具有屬性名的標簽</div> </SlotChild> </div> </template> <script> import SlotChild from 'component/slotChild' export default { name: 'slots', components:{ SlotChild }, data () { return { } } } </script>
//slot的子組件
<template> <div class="slot-child"> 我是slot的子組件 </div> </template> <script> export default { name: 'slotChild', data () { return { } } } </script>
頁面渲染效果
通過上面的內容可以知道,在slot組件中引入了slot的子組件,而且又在子組件標簽內添加了新的標簽內容,但頁面上並沒有將子組件標簽內的標簽內容顯示出來,
所以說在不適用slot的情況下,在子組件標簽內添加Dom是無效的
現在來修改slot的子組件
<template> <div class="slot-child">
//在子組件中添加slot標簽 <slot></slot> 我是slot的子組件 </div> </template> <script> export default { name: 'slotChild', data () { return { } } } </script>
頁面效果圖
由此可見,使用slot后可以在子組件內顯示插入的新標簽
具名插槽
子組件
<template> <div class="slottwo"> <div>slottwo</div> <slot name="header"></slot> <slot></slot> <slot name="footer"></slot> </div> </template>
在子組件中定義了三個slot標簽,其中有兩個分別添加了name屬性header和footer
父組件
<template> <div> 我是父組件 <slot-two> <p>啦啦啦,啦啦啦,我是賣報的小行家</p> <template slot="header"> <p>我是name為header的slot</p> </template> <p slot="footer">我是name為footer的slot</p> </slot-two> </div> </template>
在父組件中使用template並寫入對應的slot值來指定該內容在子組件中現實的位置(當然也不用必須寫到template),沒有對應值的其他內容會被放到子組件中沒有添加name屬性的slot中
插槽的默認內容
父組件
<template>
<div>
我是父組件
<slot-two></slot-two>
</div>
</template>
子組件
<template> <div class="slottwo"> <slot>我不是賣報的小行家</slot> </div> </template>
可以在子組件的slot標簽中寫入內容,當父組件沒有寫入內容時會顯示子組件的默認內容,當父組件寫入內容時,會替換子組件的默認內容
作用域插槽
子組件
<template> <div> 我是作用域插槽的子組件 <slot :data="user"></slot> </div> </template> <script> export default { name: 'slotthree', data () { return { user: [ {name: 'Jack', sex: 'boy'}, {name: 'Jone', sex: 'girl'}, {name: 'Tom', sex: 'boy'} ] } } } </script>
在子組件的slot標簽上綁定需要的值
父組件
<template> <div> 我是作用域插槽 <slot-three> <template slot-scope="user"> <div v-for="(item, index) in user.data" :key="index"> {{item}} </div> </template> </slot-three> </div> </template>
在父組件上使用slot-scope屬性,user.data就是子組件傳過來的值
v-slot
指令自 Vue 2.6.0 起被引入,提供更好的支持 slot
和 slot-scope
attribute 的 API 替代方案。在接下來所有的 2.x 版本中 slot
和 slot-scope
attribute 仍會被支持,但已經被官方廢棄且不會出現在 Vue 3 中。
vue 廢棄了 slot
和 slot-scope 推薦使用新的v-slot,上面看完簡單理解一下就行了,畢竟舊的語法到vue3.0才真正廢棄:
肯定有朋友好奇 v-slot:default是什么: 其實就是具名插槽名,默認插槽為default
還可以更簡單 像v-bind一樣 v-slot 可以簡寫為# :v-slot:header = #header
但要注意了! 和其它指令一樣,該縮寫只在其有參數的時候才可用。這意味着以下語法是無效的:
<!-- 這樣會觸發一個警告 -->
<current-user #="{ user }">
{{ user.firstName }}
</current-user>
如果你希望使用縮寫的話,你必須始終以明確插槽名取而代之:
<current-user #default="{ user }"> {{ user.firstName }} </current-user>
你甚至可以動態定義它:
注意不可以混用!:
官方提供了更便捷的 解構插槽 看一下就懂了: