一、插槽(slot):组件中的模板会覆盖组件中的原始内容(即自定义标签对内部的内容会不显示),使用插槽可以使自定义标签内容显示;
插槽作用:父组件提供内容,子组件中展示
二、插槽结构:
1.匿名插槽(单个插槽,无name属性):父组件传递到子组件的内容会覆盖掉子组件插槽中默认的内容
父组件:
<template>
<div>
<h2>小d页面视图</h2>
<h2>我是父亲</h2>
<ddSon>
默认插槽显示的内容
</ddSon>
</div>
</template>
<script setup>
import ddSon from "../components/ddSon.vue"
</script>
子组件:
<template>
<div style="background-color: #fff;">
<h3>我是孩子</h3>
<!-- 1.默认插槽: -->
<slot>默认插槽内容</slot>
</div>
</template>
<script setup>
</script>
效果:
2.具名插槽:(有name属性)
父组件:
<template>
<div>
<h2>小d页面视图</h2>
<h2>我是父亲</h2>
<ddSon>
<template v-slot:header>具名插槽显示内容:nihao</template>
//简写
<!-- <template #header>具名插槽显示内容:nihao</template> -->
</ddSon>
</div>
</template>
<script setup>
import ddSon from "../components/ddSon.vue"
</script>
子组件:
<template>
<div style="background-color: #fff;">
<h3>我是孩子</h3>
<slot name="header"></slot>
</div>
</template>
效果:
3.作用域插槽(带数据插槽)
父组件:
<template>
<div>
<h2>我是父亲</h2>
<ddSon>
<template v-slot:hhgg="ChildSlot">
{
{ChildSlot.item}}
</template>
</ddSon>
</div>
</template>
<script setup>
import ddSon from "../components/ddSon.vue"
</script>
子组件:
<template>
<div style="background-color: #fff;">
<h3>我是孩子</h3>
<ul>
<li v-for="(item,index) in items" :key="index">
<slot :item="item" name="hhgg"></slot>
</li>
</ul>
</div>
</template>
<script setup>
const items = ref(['hhh','ggg'])
</script>
效果: