1.單個插槽 | 默認插槽 | 匿名插槽
匿名插槽就是可以在父組件中的子組件的標籤中直接添加內容
子組件A:
<template>
<div class="dialog">
<div>我是A組件中的對話框<div>
<slot></slot>
</div>
</template>
<script>
export default {
name: "diolage",
props: {
options: {
type:String
}
}
}
</script>
父組件:(在組件外, 我們可以往插槽裏填入任何元素, dialog-a
爲組件的名稱)
<template>
<dialogPage :options="hello"> // 只有子組件中使用了slot才能成功在此標籤中添加內容
<button>按鈕</button>
// ... 可以是任何元素
</dialogPage>
</template>
<script>
import dialogPage from './dialog'
export default {
name: "Home",
components:{
dialogPage
},
data() {
return {
hello:'我是父組件的值'
}
}
}
</script>
2.具名插槽
具名插槽就是一個擁有name屬性的插槽,具名插槽可以在同一組件中多次使用。
子組件A:
<template>
<div class="dialog">
<div>我是A組件中的對話框<div>
<slot name="slotUp"></slot> // 具名插槽
<slot name="slotDown"></slot> // 具名插槽
<slot></slot> //匿名插槽
</div>
</template>
<script>
export default {
name: "diolage",
props: {
options: {
type:String
}
}
}
</script>
父組件:(在組件外, 我們可以往插槽裏填入任何元素, dialog-a
爲組件的名稱)
沒有slot屬性的html模板默認關聯匿名插槽。
<template>
<dialogPage :options="hello">
<template slot="slotUp">
<button>按鈕</button>
</template>
<template slot="slotDown">
<a>按鈕</a>
</template>
<template>
<a>按鈕</a>
</template>
</dialogPage>
</template>
<script>
import dialogPage from './dialog'
export default {
name: "Home",
components:{
dialogPage
},
data() {
return {
hello:'我是父組件的值'
}
}
}
</script>
3.作用域插槽 | 帶數據的插槽
作用域插槽就是一個可以攜帶數據的具名插槽,稱爲作用域插槽。
子組件A:
<template>
<div class="dialog">
<div>我是A組件中的對話框<div>
<slot name="slotData" :message="message"></slot> // 作用域插槽
<slot name="slotUp"></slot> // 具名插槽
<slot name="slotDown"></slot> // 具名插槽
<slot></slot> //匿名插槽
</div>
</template>
<script>
export default {
name: "diolage",
props: {
options: {
type:String
}
},
data(){
return {
message:'我是作用域插槽的數據'
}
}
}
</script>
父組件:(在組件外, 我們可以往插槽裏填入任何元素, dialog-a
爲組件的名稱)
沒有slot屬性的html模板默認關聯匿名插槽。
<template>
<dialogPage :options="hello">
<template slot="slotData" slot-scope="scope"> // 作用域插槽
<button>{{scope.message}}</button>
</template>
</dialogPage>
</template>
<script>
import dialogPage from './dialog'
export default {
name: "Home",
components:{
dialogPage
},
data() {
return {
hello:'我是父組件的值'
}
}
}
</script>