## 插槽
1. 说明:Vue 实现了一套内容分发的 API,定义时不知道具体要显示什么,只是留出来显示的位置,在组件调用时写具体内容,能展现在预留的位置上。
2. 定义:使用 标签预留位置
3. 调用组件时,写具体的要呈现的内容,要显示在标签中
1. 匿名插槽
<slot></slot>
<slot name='default'></slot> //相当于有默认名字
2. 具名插槽
// 定义语法:
<slot name='xx'></slot>
// 使用:
<template v-slot:xx> 内容 </template>
3. 作用域
// 说明:传递数据
// 插槽数据 传递给外部使用
<slot name="footer" :msg='msg' title='静态数据'></slot>
// 接受数据对象:
<template v-slot:xx='data'> 内容 </template>
data={msg:'',title:''}
4. 简写方式
v-slot:xxx='' 简写 #xxx=''
5. 后备数据 默认值
6. 动态插槽名
<template v-slot:[ft]="data">
<h3>我是底部:{{ data.msg }}</h3>
</template>
附录:
(1)匿名插槽
<template>
<!-- 此为父组件 -->
<div>
<p>父亲</p>
<Child>
<span>自定义内容</span>
</Child>
</div>
</template>
<script>
import Child from "../components/child.vue";
export default {
components: {
Child,
},
};
</script>
<style>
</style>
<template>
<!-- 此为子组件 -->
<div>
<p>儿子</p>
<!-- 匿名插槽 -->
<slot></slot>
</div>
</template>
<script>
export default {
data() {
return {};
},
};
</script>
<style>
</style>
运行结果:
(2)具名插槽
<template>
<!-- 此为子组件 -->
<div>
<p>儿子</p>
<!-- 具名插槽 -->
<slot name="header">默认值</slot>
</div>
</template>
<script>
export default {
data() {
return {};
},
};
</script>
<style>
</style>
<template>
<!-- 此为父组件 -->
<div>
<p>父亲</p>
<Child>
<!-- 子组件具名插槽名称header -->
<template #header>
<!-- v-slot属性(或者#)只能在<template>上面使用 -->
<h1>我不是默认值</h1>
</template>
</Child>
</div>
</template>
<script>
import Child from "../components/child.vue";
export default {
components: {
Child,
},
};
</script>
<style>
</style>
运行结果:
(3)作用域插槽
<template>
<!-- 此为子组件 -->
<div>
<p>儿子</p>
<!-- 作用域插槽 -->
<slot name="header" :data="msg">默认值</slot>
</div>
</template>
<script>
export default {
data() {
return {
msg:"子组件的信息"
};
},
};
</script>
<style>
</style>
<template>
<!-- 此为父组件 -->
<div>
<p>父亲</p>
<Child>
<!-- 子组件具名插槽名称header 自定义对象名 -->
<template #header="info">
<h1>
我接受{{info.data}}
</h1>
</template>
</Child>
</div>
</template>
<script>
import Child from "../components/child.vue";
export default {
components: {
Child,
},
};
</script>
<style>
</style>
运行结果: