一、什么是插槽
插槽就是子组件中的提供给父组件使用的一个占位符,用 <slot></slot>
表示,父组件可以在这个占位符中填充任何模板代码,如 HTML、组件等,填充的内容会替换子组件的 <slot></slot>
标签。通俗的说是:slot 是在父组建控制了子组件显示或隐藏相关内容。
二、插槽的分类
- 默认插槽 : 没写属性,则默认属性为 v-slot=default 表示默认
- 具命插槽 : 写了属性指定slot名字,则为具名插槽
- 作用域插槽 :作用域插槽的样式由父组件决定,内容却由子组件控制。前两种插槽不能绑定数据,作用域插槽是一个带绑定数据的插槽。简单的来说就是子组件提供给父组件参数,该参数仅限于插槽中使用,父组件可以根据子组件传过来的插槽数据来进行不同的方式展现和填充插槽的内容。
三、默认插槽
1、在子组件中放一个占位符
<template>
<div>
<h1>今天天气状况:</h1>
<slot></slot>
</div>
</template>
<script>
export default {
name: 'child'
}
</script>
2、在父组件中给这个占位符填充内容
<template>
<div>
<div>使用slot分发内容</div>
<div>
<child>
<div style="margin-top: 30px">多云,最高气温34度,最低气温28度,微风</div>
</child>
</div>
</div>
</template>
<script>
import child from "./child.vue";
export default {
name: 'father',
components:{
child
}
}
</script>
四、具名插槽
1、子组件的代码,设置了两个插槽(header和footer):
<template>
<div>
<div class="header">
<h1>我是页头标题</h1>
<div>
<slot name="header"></slot>
</div>
</div>
<div class="footer">
<h1>我是页尾标题</h1>
<div>
<slot name="footer"></slot>
</div>
</div>
</div>
</template>
<script>
export default {
name: "child1"
}
</script>
<style scoped>
</style>
2、父组件填充内容, 父组件通过 v-slot:[name] 的方式指定到对应的插槽中
<template>
<div>
<div>slot内容分发</div>
<child1>
<template slot="header">
<p>我是页头的具体内容</p>
</template>
<template slot="footer">
<p>我是页尾的具体内容</p>
</template>
</child1>
</div>
</template>
<script>
import child1 from "./child1.vue";
export default {
name: "father1",
components: {
child1
}
}
</script>
<style scoped>
</style>
五、作用域插槽
vue 中的作用域插槽可以让父组件使用插槽时插槽内容能够访问子组件中的数据
1.子组件
<template>
<div class="category">
<h3>{{title}}分类</h3>
<slot :games="games" msg="hello">我是默认的一些内容</slot>
</div>
</template>
<script>
export default {
name:'Category',
props:['title'],
data() {
return {
games:['红色警戒','穿越火线','劲舞团','超级玛丽'],
}
},
}
</script>
<style scoped>
.category{
background-color: skyblue;
width: 200px;
height: 300px;
}
h3{
text-align: center;
background-color: orange;
}
video{
width: 100%;
}
img{
width: 100%;
}
</style>
2.父组件
<template>
<div class="container">
<Category title="游戏">
<template scope="atguigu">
<ul>
<li v-for="(g,index) in atguigu.games" :key="index">{{g}}</li>
</ul>
</template>
</Category>
<Category title="游戏">
<template scope="{games}">
<ol>
<li style="color:red" v-for="(g,index) in games" :key="index">{{g}}</li>
</ol>
</template>
</Category>
<Category title="游戏">
<template slot-scope="{games}">
<h4 v-for="(g,index) in games" :key="index">{{g}}</h4>
</template>
</Category>
</div>
</template>
<script>
import Category from './components/Category'
export default {
name:'App',
components:{Category},
}
</script>
<style scoped>
.container,.foot{
display: flex;
justify-content: space-around;
}
h4{
text-align: center;
}
</style>