什么是插槽
插槽就是子组件提供给父组件的一个占位符, 应用<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. 如果子组件有多个默认插槽,而父组件所有指定到默认插槽的填充内容,将“会” “全都”填充到子组件的每个默认插槽中。