1

什么是插槽

插槽就是子组件提供给父组件的一个占位符, 使用<slot></slot>表示, 父组件可以在这个占位符里填充任何模板代码, 比如html 组件等,填充的内容会替换子组件里的slot标签
子组件

<template>
    <div>
    <p>今天天气</p>
    <slot></slot>
    </div>
</template>

父组件

<div>
    <p>使用slot分发内容</p>
    <SlotChild>天气真不错</SlotChild>
</div>
如果子组件没有使用插槽,父组件如果需要往子组件中填充模板或者html, 是没法做到的

具名插槽

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

<template>
    <div>
        <div>
            <h1>我是页头</h1>
            <slot name="header"></slot>
        </div>
        <div>
            <h1>我是页尾</h1>
            <slot name="footer"></slot>
        </div>
    </div>
</template>
<div>
    <SlotChild>
        <template v-slot:header>
            <h1>展示页头相关内容</h1>
        </template>
        <template v-slot:footer>
            <h1>展示页尾相关内容</h1>
        </template>
    </SlotChild>
</div>

默认插槽

默认插槽就是指没有名字的插槽, 子组件未定义的名字的插槽,父级将会把 未指定插槽的填充的内容填充到默认插槽中。

<div>
    <div>
        <h1>我是页头</h1>
        <slot name="header"></slot>
    </div>
    <div>
        <h1>我是未定义插槽</h1>
        <slot></slot>
    </div>
    <div>
        <h1>我是页尾</h1>
        <slot name="footer"></slot>
    </div>
</div>
<div>
    <SlotChild>
        <template v-slot:header>
            <h1>展示页头相关内容</h1>
        </template>
        <template>
            <h1>未定义名字插槽</h1>
        </template>
        <template v-slot:footer>
            <h1>展示页尾相关内容</h1>
        </template>
    </SlotChild>
</div>

注意

1.  父级的填充内容如果指定到子组件的没有对应名字插槽,那么该内容不会被填充到默认插槽中。
2.  如果子组件没有默认插槽,而父级的填充内容指定到默认插槽中,那么该内容就“不会”填充到子组件的任何一个插槽中。
3.  如果子组件有多个默认插槽,而父组件所有指定到默认插槽的填充内容,将“” “全都”填充到子组件的每个默认插槽中。


lolo
12 声望0 粉丝