vue插槽slot的用法
什么是插槽?
插槽就是子组件提供给父组件的一个占位符,当父组件使用子组件需要填充一些代码片段或者内容的时候可以使用slot进行占位填充。父组件中的内容就会将子组件中的slot替换。
1.简单举例
子组件
<template>
<div>
<h1>这是插槽的简单用法</h1>
<div style="margin-top:30px;font-size:20px;">
<slot></slot>
</div>
</div>
</template>
父组件
<template>
<div>
<Child>
<div>简单用法简单用法简单用法</div>
</Child>
</div>
</template>
效果
父组件中的代码片段替换了子组件中的slot
2.具名插槽(也就是带名称的插槽<slot name=“xxx”></slot>)
在父组件中使用子组件时,可能有不止一个地方使用插槽,这个时候就要使用具名插槽。如果不带名称的话,就不知道对应的是哪个地方。
子组件
<template>
<div>
<div>
<h1>这是子组件的头部插槽</h1>
<div style="margin-top:20px;font-size:20px;">
<slot name="header"></slot>
</div>
</div>
<div style="margin-top:30px;">
<h1>这是子组件的尾部插槽</h1>
<div style="margin-top:20px;font-size:20px;">
<slot name="footer"></slot>
</div>
</div>
</div>
</template>
父组件
<template>
<div>
<Child>
<div v-slot="header">头部头部头部</div