插槽
<slot>
元素底洗,承載分發(fā)內(nèi)容的出口涩澡。或者理解為占位符
票摇,當父組件引用子組件時可以填充相應內(nèi)容拘鞋。
子組件<item-d>
<div class="demo">
<slot></slot>
</div>
父組件
<item-d>
插槽內(nèi)容
</item-d>
當然插槽內(nèi)可以包含任何模板代碼,包括 HTML
如下父組件引用<item-d>
時插入個按鈕
<item-d>
<button @click="account++">{{account}}</button>
</item-d>
編譯作用域
在上例中矢门,<button>
是作為父組件的內(nèi)容進行編譯的盆色,所以可以訪問父組件的實例屬性account
。
后備內(nèi)容
插槽的默認內(nèi)容祟剔。當父組件使用子組件不提供插槽內(nèi)容時隔躲,默認顯示插槽的后備內(nèi)容
在<item-d>
組件中
<div>
<slot>這是默認顯示內(nèi)容</slot>
</div>
父組件
<item-d></item-d>
<item-d>
父組件提供插槽內(nèi)容
</item-d>
具名插槽
當子組件中有多個插槽時,想將不同的內(nèi)容顯示到對應插槽中物延,則要借助于<slot>
的name
屬性蹭越。
在子組件<item-d>
中
<div class="demo">
<slot name="s1">插槽一</slot>
<slot>插槽二</slot>
<slot>
<h1>1</h1>
</slot>
</div>
父組件
<item-d>
<template v-slot:s1>1</template>
<template>2</template>
未定義
<template v-slot:s1>3</template>
</item-d>
在父組件中,
<template>2</template>
及未定義
都沒有設置v-slot教届,默認屬于default
插槽响鹃,而<template v-slot:s1>1</template>
和<template v-slot:s1>3</template>
屬于同一個具名插槽;子組件中案训,<slot>插槽二</slot>
和<slot><h1>1</h1></slot>
都是default
插槽买置;在實際頁面顯示中可以看到2 未定義
出現(xiàn)了兩次,即default
插槽使用了兩次强霎,而s1
插槽的位置上顯示的是3
忿项,則說明在父組件引用子組件時,后面的覆蓋了前面的s1
插槽(或者說重定義)城舞。
- 沒有設置
name
屬性值時轩触,默認為default
- 父組件引用子組件時,任何沒有被包裹在帶有
v-slot
的<template>
中的內(nèi)容都會被視為默認插槽的內(nèi)容 - 如果出現(xiàn)相同
v-slot
的<template>
家夺,后面的會覆蓋前面的
作用域插槽
父組件通過插槽訪問子組件的數(shù)據(jù)脱柱。子組件在<slot>
元素上綁定的屬性稱為插槽prop
,父組件使用v-slot
指令定義插槽prop
拉馋。定義的屬性只能在對應的<template>
中使用榨为,即作用域只在當前的<template>
中有效惨好。
和父組件向子組件通信的prop
類似:將要訪問的數(shù)據(jù)綁定到元素屬性,然后在引用的地方“聲明”下随闺。
子組件
<div class="demo">
<slot name="s1" :title="title"></slot>
</div>
...
export default {
data(){
return {
title:'標題'
}
}
}
父組件
<item-d>
<template v-slot:s1="t1">{{t1.title}}</template>
</item-d>
其它
- 父組件使用
v-slot
指令定義插槽prop
日川,只在其<template>
中有效。 - 若子組件中只有默認插槽矩乐,如
v-slot:default="t1"
可以簡寫成v-slot="t1"
龄句;當同時存在具名插槽
時,則不能這樣簡寫(作用域不明確)散罕。 -
v-slot:
可以簡寫成#
撒璧,v-slot="t1"
可以簡寫成#default="t1"
,v-slot:s1
可以簡寫成#s1
笨使。(縮寫只在其有參數(shù)的時候才可用)卿樱。 - 支持動態(tài)的插槽名,如在父組件內(nèi)
s="s1"
硫椰,則#[s]
等同于#s1
繁调,當然變量s
的值要是個字符串。