未命名插槽
slot未命名時(shí),每個(gè)<slot>標(biāo)簽內(nèi)都會(huì)生成父組件中提供的內(nèi)容羽杰。
父組件app.vue
<template>
<div id='app'>
<slottest>
<h1>Here might be a page title</h1>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
<p>Here's some contact info</p>
</slottest>
</div>
</template>
<script>
import slottest from './components/slottest'
export default {
data(){
return {
}
},
components:{
slottest
}
}
</script>
子組件slottest.vue
<template>
<div>
<slot></slot>
<slot></slot>
</div>
</template>
<script>
export default {
data(){
return {
}
}
}
</script>
<style>
</style>
渲染HTML如下
image.png
如果子組件中沒有包含任何一個(gè) <slot> 元素综苔,則任何傳入它的內(nèi)容都會(huì)被拋棄圃阳。
命名插槽
父組件app.vue
<template>
<div id='app'>
<button-counter></button-counter>
<slottest>
<h1 slot="header">Here might be a page title</h1>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
<p slot="footer">Here's some contact info</p>
</slottest>
</div>
</template>
<script>
import slottest from './components/slottest'
export default {
data(){
return {
}
},
components:{
slottest
}
}
</script>
子組件slottest.vue
<template>
<div>
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
</template>
<script>
export default {
data(){
return {
}
}
}
</script>
<style>
</style>
渲染完后html結(jié)構(gòu)
image.png
默認(rèn)內(nèi)容
<button type="submit">
<slot>Submit</slot>
</button>
如果父組件為這個(gè)插槽提供了內(nèi)容紊撕,則默認(rèn)的內(nèi)容會(huì)被替換掉蜡歹。
作用域插槽 | 帶數(shù)據(jù)的插槽
作用域插槽要求赂乐,在slot上面綁定數(shù)據(jù)薯鳍。
<slot name="up" :data="data"></slot>
export default {
data: function(){
return {
data: ['zhangsan','lisi','wanwu','zhaoliu','tianqi','xiaoba']
}
},
}
父組件
<template>
<div class="father">
<h3>這里是父組件</h3>
<!--第一次使用:用flex展示數(shù)據(jù)-->
<child>
<template slot-scope="user">
<div class="tmpl">
<span v-for="item in user.data">{{item}}</span>
</div>
</template>
</child>
<!--第二次使用:用列表展示數(shù)據(jù)-->
<child>
<template slot-scope="user">
<ul>
<li v-for="item in user.data">{{item}}</li>
</ul>
</template>
</child>
<!--第三次使用:直接顯示數(shù)據(jù)-->
<child>
<template slot-scope="user">
{{user.data}}
</template>
</child>
<!--第四次使用:不使用其提供的數(shù)據(jù), 作用域插槽退變成匿名插槽-->
<child>
我就是模板
</child>
</div>
</template>
子組件
<template>
<div class="child">
<h3>這里是子組件</h3>
// 作用域插槽
<slot :data="data"></slot>
</div>
</template>
export default {
data: function(){
return {
data: ['zhangsan','lisi','wanwu','zhaoliu','tianqi','xiaoba']
}
}
}
image.png