vue插槽理解

什么是插槽

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

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

父组件code

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

具名插槽

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

<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.  若是子组件有多个默认插槽,而父组件全部指定到默认插槽的填充内容,将“” “全都”填充到子组件的每一个默认插槽中。di