一、基本的插槽
這里總結兩點
slot 代表父組件往子組件中 插入的標簽
這里就代表組件子組件中的
<p>Dell</p><child><p>Dell</p></child>
這里如果是這樣的
<child> </child>
就會顯示 <slot>默認內容</slot>中的默認內容
二、聚類插槽
1、如果不在子組件中使用插槽(slot),那么在子組件中寫任何代碼都是無效的的,不會顯示
2、(插槽默認值)如果子組件中沒有插入任何代碼的話就會顯示組件插槽中的內容
這里如果是這樣的
<child> </child>
就會顯示<slot>默認內容</slot>中的 默認內容
3、聚類插槽
子組件這么寫:
template:`<div><slot>默認內容</slot><p>content</p><slot>默認內容</slot></div>
然后這么引用:
<child> <div>header</div> <div>footer</div></child>
就會發現結果是
header
footer
content
header
footer
這個不是我的本意,那么怎么辦,這里就引入了聚類插槽
子組件:
template:`<div><slot name='header'>默認內容</slot><p>content</p><slot name='footer'>默認內容</slot></div>`
子組件引用:
<child><div slot='header'>header</div><div slot='footer'>footer</div></child>
不難發現給每個想要指定的子組件插槽添加 name屬性,然后在引用中 slot中明確 是哪個即可也可以理解為引用中是用了兩個插槽同時,默認內容同時適用在每個插槽
三、作用域插槽
這個是普通插槽的Demo
<!DOCTYPE html><html><head> <meta charset="utf-8"> <title>Vue中使用插槽(slot)</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script></head><body> <div id="root"> <!-- 1、如果不在子組件中使用插槽(slot),那么在子組件中寫任何代碼都是無效的的,不會顯示 2、(插槽默認值)如果子組件中沒有插入任何代碼的話就會顯示組件插槽中的內容 這里如果是這樣的 <child> </child> 就會顯示 <slot>默認內容</slot>中的 默認內容 --> <child> <p>Dell</p> </child> </div> <script type="text/javascript"> Vue.component('child',{ /* slot 代表 父組件往子組件中 插入的標簽 這里就代表 組件子組件中的 <p>Dell</p> <child> <p>Dell</p> </child> */ template:`<div> <slot>默認內容</slot> </div>` }); var vm = new Vue({ el:'#root', }); </script></body></html>
新聞熱點
疑難解答
圖片精選