1、什么是插槽
插槽(Slot)是 Vue 提出来的一个概念,插槽用于决定将所携带的内容,插入到指定的某个位置,具有模块化的特质和更大的重用性。插槽显不显示、怎样显示是由父组件来控制的,而插槽在哪里显示就由子组件来进行控制
2、插槽分类
插槽一般可分为三大类:匿名插槽(默认插槽)、具名插槽、作用于插槽,语法如下:
<slot></slot>
3、匿名插槽使用示例
<template>
<h1>这是一个子组件</h1>
<slot></slot>
<slot></slot>
</template>
<template>
<h1>这是父组件</h1>
<Son>
<p style="color: red;">匿名(默认)插槽数据</p>
<p style="color: yellow;">匿名(默认)插槽数据</p>
</Son>
</template>
运行结果:
4,具名插槽使用示例
<template>
<h1>这是一个子组件</h1>
<slot name="s"></slot>
</template>
<template>
<h1>这是父组件</h1>
<Son>
<template v-slot='s'>
<!--简写用‘#’代替‘v-slot’
<template #s>-->
<p style="color: greenyellow;">具名插槽</p>
</template>
</Son>
</template>
运行结果:
5、作用域插槽(可用于子组件向父组件传值)
<template>
<h1>这是一个子组件</h1>
<slot name="s" :userInfo="userInfo" :xingming="name"></slot>
</template>
<template>
<h1>这是父组件</h1>
<Son>
<!-- <p style="color: red;">匿名(默认)插槽数据</p>
<p style="color: yellow;">匿名(默认)插槽数据</p> -->
<template #s="mprops">
<p style="color: greenyellow;">具名插槽---{{mprops.userInfo.name}}----- {{mprops.userInfo.age}}</p>
<p style="color: greenyellow;">具名插槽---{{mprops.xingming}}</p>
</template>
</Son>
</template>
运行结果:
6、动态插槽,这里就不具例子了,其实就是把具名插槽的name用一个变量替代,根据变量取值来觉得用那个具名插槽显示。
如有不足之处,请提出共同交流学习!