插槽是vue为组件的封装者提供的能力。允许开发者在封装组件时,把不确定的,希望由用户指定的部分定义为插槽。
后备内容:
封装组件时,可以为<slot>插槽提供后备内容(默认内容)。如果组件的使用者没有为插槽提供任何内容,则后备内容会生效。
1.插槽v-slot(简写:#)的使用:
<template lang="">
<div>
<h1>根组件</h1>
<child>
<!-- 正常情况下,这句话是在页面不被显示的 -->
<!-- 默认情况下,在使用组件的时候,提供的内容都会被填充到名为default的插槽中 -->
<!-- 如果想要把p标签内容放到指定插槽,要在template加上v-slot:名称,不能直接将v-slot写到p标签之上,会直接报错 -->
<!-- v-slot:default简写#default -->
<template #default>
<p>我是在child区域声明的p标签</p>
</template>
</child>
</div>
</template>
<script>
import child from "@/components/child.vue"
export default{
components:{
child
}
}
</script>
<!-- 注:template只起到一个包括的作用,不会被渲染到页面-->
<template lang="">
<div>
<!-- 当在子组件声明一个插槽区域,根组件的<child>标签的内容就可以被显示 -->
<!-- vue官方规定,每一个solt插槽,都要有一个name名称
如果省略了name属性,则有一个默认名称default
-->
<!--这是插槽的内容区域 这句话是默认值,
只有根标签中的child未定义内容时显示,定义时以child包裹内容为主 -->
<slot name="default"> <p>这是插槽的内容区域</p> </slot>
</div>
</template>
<script>
</script>
2.具名插槽:(对应的内容区域要对应插槽的名称,否则默认放到未定义name的default插槽)
<template lang="">
<div >
<h1>根组件</h1>
<child>
<template #title>
<p>标题</p>
</template>
<template #center>
<p>内容</p>
</template>
<template #foot>
<p>尾部</p>
</template>
</child>
</div>
</template>
<script>
import child from "@/components/child.vue"
export default {
components: {
child
}
}
</script>
<template lang="">
<div class="contain-box">
<div class="header-box"><slot name="title"></slot></div>
<div class="center-box" ><slot name="center"></slot></div>
<div class="footer-box"><slot name="foot"></slot></div>
</div>
</template>
<script>
</script>
<style lang="less" scoped>
.contain-box{
height: 150px;
.header-box{
height: 50px;
background-color: antiquewhite;
}
.center-box{
height: 50px;
background-color: aquamarine;
}
.footer-box{
height: 50px;
background-color: chocolate;
}
}
</style>
3.作用域插槽:
<template lang="">
<div >
<h1>根组件</h1>
<child>
<!-- 所有内容全部传递给了obj,此处也可以使用解构 -->
<template #title="obj">
<p>{{obj.msg}}</p>
<p>{{obj.user.age}}</p>
</template>
</child>
</div>
</template>
<script>
import child from "@/components/child.vue"
export default {
components: {
child
}
}
</script>
<template lang="">
<div class="contain-box">
<div class="header-box">
<!-- 在封装组件时,为预留的<slot>提供对应的值,这种用法叫做 作用域插槽 -->
<slot name="title" msg="一个穿云箭" :user="users"></slot>
</div>
</div>
</template>
<script>
export default{
data(){
return{
users:{
name:"张三",
age:18
}
}
}
}
</script>
<style lang="less" scoped>
.contain-box{
height: 150px;
.header-box{
height: 50px;
background-color: antiquewhite;
}
}
</style>