slot:向组件内部指定位置传递内容
- 单个插槽(匿名插槽)
在App.vue引入子组件About.vue,在about标签加上一个div标签传递到子组件中:
App.vue
<template>
<div id="root">
<about>
<div>hello world!</div>
</about>
</div>
</template>
<script>
import About from "./views/About.vue"
export default {
components:{
About
},
</script>
About.vue通过slot标签获取父组件传递过来的div标签:
<template>
<div class="about">
这是about组件
<slot></slot>
</div>
</template>
- 多个插槽(具名插槽)
App.vue
<template>
<div id="root">
<about>
<div slot="t1">hello world!</div>
<div slot="t2">hello I!</div>
<div slot="t3">hello You!</div>
</about>
</div>
</template>
About.vue
<template>
<div class="about">
这是about组件
<slot name="t1"></slot>
<slot name="t2"></slot>
<slot name="t3"></slot>
</div>
</template>
- 作用域插槽
子组件提供数据,父组件调用子组件,提供样式排版
App.vue
<template>
<div id="root">
<!-- 第一次调用about组件 -->
<about>
<template slot-scope="scores">
<ul class="about1">
<li v-for="item in scores.list" :key="item">{{item.name}}: {{item.score}}</li>
</ul>
</template>
</about>
<!-- 第二次调用about组件 -->
<about>
<template slot-scope="scores">
<span class="about2" v-for="item in scores.list" :key="item">
{{item.name}}: {{item.score}}
</span>
</template>
</about>
</div>
</template>
<script>
import About from "./views/About.vue"
export default {
components:{
About
},
}
</script>
<style lang="less">
.about1,.about1 li{
list-style: none;
}
.about1 li{
line-height: 40px;
border-bottom: 1px solid #999
}
.about2{
display: inline-block;
margin-right: 10px;
color: red
}
.about2:after{
content: '/';
padding-left: 10px;
}
</style>
About.vue
<template>
<div class="about">
这是about组件
<slot :list="list"></slot>
</div>
</template>
<script>
export default {
data(){
return{
list:[
{
name :'jack',
score : 80
},
{
name :'alice',
score : 90
},
{
name :'kate',
score : 100
}
]
}
},
}
</script>