学习Vue3 第十七章(插槽slot)

223 阅读1分钟

插槽就是子组件中的提供给父组件使用的一个占位符,用 表示,父组件可以在这个占位符中填充任何模板代码,如 HTML、组件等,填充的内容会替换子组件的标签。

匿名插槽

1.在子组件放置一个插槽

<template>
    <div>
       <slot></slot>
    </div>
</template>

父组件使用插槽

在父组件给这个插槽填充内容

    <Dialog>
       <template v-slot>
           <div>2132</div>
       </template>
    </Dialog>

具名插槽·

具名插槽其实就是给插槽取个名字。一个子组件可以放多个插槽,而且可以放在不同的地方,而父组件填充内容时,可以根据这个名字把内容填充到对应插槽中

    <div>
        <slot name="header"></slot>
        <slot></slot>

        <slot name="footer"></slot>
    </div>

父组件使用需对应名称

    <Dialog>
        <template v-slot:header>
           <div>1</div>
       </template>
       <template v-slot>
           <div>2</div>
       </template>
       <template v-slot:footer>
           <div>3</div>
       </template>
    </Dialog>

插槽简写

    <Dialog>
        <template #header>
           <div>1</div>
       </template>
       <template #default>
           <div>2</div>
       </template>
       <template #footer>
           <div>3</div>
       </template>
    </Dialog>

作用域插槽

在子组件动态绑定参数 派发给父组件的slot去使用

    <div>
        <slot name="header"></slot>
        <div>
            <div v-for="item in 100">
                <slot :data="item"></slot>
            </div>
        </div>
 
        <slot name="footer"></slot>
    </div>

通过结构方式取值

     <Dialog>
        <template #header>
            <div>1</div>
        </template>
        <template #default="{ data }">
            <div>{{ data }}</div>
        </template>
        <template #footer>
            <div>3</div>
        </template>
    </Dialog>

动态插槽

插槽可以是一个变量名

    <Dialog>
        <template #[name]>
            <div>
                23
            </div>
        </template>
    </Dialog>
const name = ref('header')

转载自:blog.csdn.net/qq119556631…

作者:小满