作用:让父组件可以向子组件中任意位置插入html结构,也是组件通信方式的一种,适用于父组件===》子组件
分类: 默认插槽、具名插槽、作用域插槽
定义子组件时使用slot组件,在使用子组件是可以决定是否插入具体的html代码
如果在使用子组件插入具体的html代码,那么slot中就会替换成对应的内容
如果使用时没有出入具体的html代码,那么就会使用slot中默认定义的内容
<template id="page">
<div>
<h1>头部导航栏h1>
<p>
<slot>我是默认内容slot>
p>
<h1>底部导航栏h2>
div>
template>
<alert-com>
<p>我是父组件中定义的内容p>
alert-com>
Vue.component('alert-com',{
template:'#page',
})

<template id="page">
<div>
<h1>头部导航栏h1>
<p>
<slot>我是默认内容slot>
p>
<h1>底部导航栏h2>
div>
template>
<alert-com1 >alert-com1>
Vue.component('alert-com1',{
template:'#page',
})

在定义子组件时可以定义很多slot插槽,并且可以命名。在父组件中使用子组件可以使用slot="center"使用命名可以来选择对应插槽的部分和内容
父组件中:
<Category>
<template slot="center">
<div>html结构1div>
template>
<template v-slot:footer>
<div>html结构2div>
template>
Category>
子组件中:
<template>
<div>
<slot name="center">插槽默认内容...slot>
<slot name="footer">插槽默认内容...slot>
div>
template>
数据在组件自身(子组件),但是数据的生成结构由组件使用者(父组件决定)
(games数据在Category(子)组件中,但使用数据所遍历出来的结构由App(父)组件决定)
由案例可知子组件传值给父组件,子组件中可以通过slot-scope =‘xxx’ (简写 scope=‘xxx’)把数据接收到xxx的对象中
父组件中:
<Category>
<template scope="scopeData">
<ul>
<li v-for="g in scopeData.games" :key="g">{{g}}li>
ul>
template>
Category>
<Category>
<template slot-scope="scopeData">
<h4 v-for="g in scopeData.games" :key="g">{{g}}h4>
template>
Category>
子组件中:
<template>
<div>
<slot :games="games">slot>
div>
template>
<script>
export default {
name:'Category',
props:['title'],
//数据在子组件自身
data() {
return {
games:['红色警戒','穿越火线','劲舞团','超级玛丽']
}
},
}
script>