Slot for communication between components in vue3

1. Slot : The template in the component will overwrite the original content in the component (that is, the custom label will not display the internal content). Use the slot to display the custom label content;

Slot function : the parent component provides content and is displayed in the child component

2. Slot structure :

1. Anonymous slot (single slot, no name attribute): The content passed from the parent component to the child component will overwrite the default content in the child component slot.

Parent component:

<template>
    <div>
        <h2>小d页面视图</h2>
        <h2>我是父亲</h2>
        <ddSon>
            默认插槽显示的内容
        </ddSon>
    </div>
</template>

<script setup>
import ddSon from "../components/ddSon.vue"
</script>

Subassembly:

<template>
<div style="background-color: #fff;">
    <h3>我是孩子</h3>
    <!-- 1.默认插槽: -->
    <slot>默认插槽内容</slot>
</div>

</template>

<script setup>
</script>

Effect:

 2. Named slot: (with name attribute)

Parent component:

<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>

Subassembly:

<template>
<div style="background-color: #fff;">
    <h3>我是孩子</h3>
    <slot name="header"></slot>
</div>

</template>

Effect:

 3. Scope slot (with data slot)

Parent component:

<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>

Subassembly:

<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>

Effect:

Guess you like

Origin blog.csdn.net/limif/article/details/127207594