slot是什么?
slot俗称“插槽”,可以通过其向组件内部指定位置传递内容。
slot能够解决什么问题?
在正常的开发情况下,如果存在以下子组件child.vue,
child.vue
<template>
<div>
Hello World
</div>
</template>
假如我们在父组件中这样引用它
parent.vue
<template>
<div>
<child>Hello Vue</child>
</div>
</template>
则渲染结果为:Hello World
即组件标签<child>Hello Vue</child>中包含的Hello Vue会被子组件模板替换掉,但开发中有时候会需要将父组件中的数据引入到子组件中去显示,此时就需要用到slot。如下,在子组件中添加插槽<slot></slot>为父组件中的Hello Vue占位,使其在此处显示。
child.vue
<template>
<div>
Hello World
<slot></slot>
</div>
</template>
渲染结果:Hello World Hello Vue
通过上面的简单描述应该就能够大致理解slot的使用和作用。
具名插槽
具名插槽,顾名思义是带有名字slot,而上面部分提到的slot我们可以看到只是简单的<slot></slot>。
在有些时候,我们需要不止添加一个slot,此时就需要用到具名插槽,根据名称相对应的关系来定义多个插槽。
假设有这样一个需求:
BaseLayout.vue
<template>
<div class="container">
<header>
<!-- 我们希望把页头放这里 -->
</header>
<main>
<!-- 我们希望把主要内容放这里 -->
</main>
<footer>
<!-- 我们希望把页脚放这里 -->
</footer>
</div>
</template>
对于这种情况,<slot>标签有一个特殊的属性:name,这个属性可以用来标记区分多个插槽
BaseLayout.vue
<template>
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
</template>
在向具名插槽提供内容的时候,我们有两种方法:
1.可以在父组件的<template>元素中使用slot属性
parent.vue
<base-layout>
<template slot="header">
<h1>Here might be a page title</h1>
</template>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
<template slot="footer">
<p>Here's some contact info</p>
</template>
</base-layout>
2.直接在普通元素上使用slot属性
parent.vue
<base-layout>
<h1 slot="header">Here might be a page title</h1>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
<p slot="footer">Here's some contact info</p>
</base-layout>
可以看到,在这三个插槽中,我们还是保留了一个未命名插槽,这个插槽是默认插槽,也就是说它会作为所有未匹配到插槽的内容的统一出口
上述两种方式渲染出来的html都将会是
<div class="container">
<header>
<h1>Here might be a page title</h1>
</header>
<main>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
</main>
<footer>
<p>Here's some contact info</p>
</footer>
</div>
插槽的默认内容
有的时候为插槽提供默认的内容是很有用的。例如,一个 <submit-button>
组件可能希望这个按钮的默认内容是“Submit”,但是同时允许用户覆写为“Save”、“Upload”或别的内容。
你可以在组件模板里的 <slot>
标签内部指定默认的内容来做到这一点。
<button type="submit">
<slot>Submit</slot>
</button>
如果父组件为这个插槽提供了内容,则默认的内容会被替换掉。
作用域插槽
推荐这篇文章https://www.jianshu.com/p/a0a83029a217,看完我理解了~