Slots in vue (anonymous slots, named slots, scoped slots)

The understanding of slot: it is a 'placeholder', which occupies a good position in the component template. When the component label is used, the content in the component label will be automatically filled (replacing the position in the component template). First prepare two
components : Father.vue and children.vue components
Introduce children.vue components in Father.vue components

<script>
import Children from '../components/children.vue'
export default {
    
    
    components:{
    
    
        Children
    }
}
</script>

Use of slot:
1. Anonymous slot (default slot)

//在Father.vue组件中写
<template>
<div>
    这是父组件
    <children>
        <div style="background:red">
            这是插槽练习,这是父组件中引入的children组件标签里的内容,这段话会通过	slot插槽显示,如果children组件中没有slot标签,这段话就不会显示
        </div>
    </children>
    <div>
        该标签内容在children标签下面,会正常显示
    </div>
</div>
</template>

<script>
import Children from '../components/children.vue'
export default {
    
    
    components:{
    
    
        Children
    }
}
</script>

//Write in the children.vue component

<template>
<div class="children">
    这是子组件中的内容
    //匿名插槽
    <slot></slot>
</div>
</template>

2. Named slots

//在Father.vue组件中写
<template>
<div>
    这是父组件
    <children>
        <!-- 具名插槽 -->
        <template v-slot:header>
            <div>
                这是具名插槽header,看看我的位置,children组件中具名插槽header在slot1的下面
            </div>
        </template>
        <template v-slot:slot1>
            <div style="border:1px solid green"  >
                我是具名插槽slot1
            </div>
        </template>
    </children>
    <div>
        该标签内容在children标签下面,会正常显示
    </div>
</div>
</template>

//Write in the children.vue component

<template>
<div class="children">
    这是子组件中的内容
    <!-- 具名插槽 -->
    <slot name="slot1"></slot>
    <slot name="header"></slot>
</div>
</template>

3. Scoped slots

//在Father.vue组件中写
<template>
<div>
    这是父组件
    <children>
        <!-- 作用域插槽 -->
        <template v-slot:name1="aa" >
            <ul>
                <li
                    v-for="item in aa.data" :key="item"
                >
                {
    
    {
    
    item}}
                </li>
            </ul>
        </template>
    </children>
    <div>
        该标签内容在children标签下面,会正常显示
    </div>
</div>
</template>

//Write in the children.vue component

<template>
<div class="children">
    这是子组件中的内容
   	//作用域插槽
    <slot name="name1" :data="data"></slot>
</div>
</template>

Guess you like

Origin blog.csdn.net/ccyolo/article/details/116536799