VUE2中的插槽
什么是插槽
插槽是什么,其实插槽就是子组件中的提供给父组件的一个占位符,用表示,父组件可以在这个占位符中填充任何模板代码,如HTML,组件等,填充的内容会替换子组件的标签。
[Vue2插槽](https://v2.cn.vuejs.org/v2/guide/components-slots.html#ad)我们首先要知道的是什么是插槽?
答:父子组件之间的一种通信方式,父组件给子组件传html和css
插槽都有哪几种?
答:分为普通插槽,具名插槽,作用域插槽
我们一一来进行讲解(分别用了两种解释方式)
普通插槽
// 子组件Child中
<slot>默认内容,在父组件没有使用默认插槽的时候</slot>
//在父组件App中
//简写格式
<Child> 组件标签之间的内容会被渲染到子组件的slot标签位置 </Child>
//全写
<Child>
<template v-slot:default> 组件标签之间的内容会被渲染到子组件的slot标签位置 </template> </Child>
1.在子组件中使用slot标签开一个槽,slot标签中的内容默认展示
2.在父组件间中,写子组件标签的时候,在子组件标签之间写的内容会放在槽里面 存在的问题:
当子组件中开多个槽的时候,组件标签之间的内容会给每个槽都放上
如何解决?
具名插槽
具名插槽
//在子组件Child中
<slot name='qwer'></slot>
//在父组件中 -App
<Child>
<template v-slot:qwer> 具名插槽 </template>
</Child>
子组件
<slot name="qwer">我们不合适</slot>
slot标签添加name数据,给slot标签起个名字
父组件
<Child>
<template v-slot:qwer>
<div>这天真热</div>
</template>
</Child>
在组件表标签之间写的内容加 v-slot 指令, :qwer 冒号之后的qwer是插槽的名字
问题:
在子组件中由数据,这个数据呢决定插槽的内容,此时怎么办?
使用作用域插槽
作用域插槽
//子组件 - Child
<slot :userinfo="userinfo" :intro="intro" abc="i love you"><slot>
:userinfo="userinfo" slot标签的属性(除了name属性)会收集起来变成一个对象,供父组件写插槽内容的时候使用
//父组件 - App
<Child>
<template v-slot="scope">
{{ scope.userinfo }}
{{ scope.intro }}
{{ scope.abc }}
</template>
</Child>
<Child>
<template v-slot="{ userinfo, intro, abc }">
{{ userinfo }}
{{ intro }}
{{ abc }}
</template>
</Child>
注意: v-slot指令有简写,简写成#,v-slot:qwer="scope" ----> #qwer="scope"
当插槽单独使用的时候,template标签是可以省略的
作用域插槽
由子组件的数据决定父组件的模板内容
子组件:
<slot name="abc" :asdf="userinfo" :intro="intro">年薪百万</slot>
slot标签上绑定父组件需要的数据
父组件:
<Child>
<template v-slot:abc="{ asdf, intro }">
<div>用户名: {{ asdf.username }}</div>
<div>年龄: {{ asdf.age }}</div>
<div>介绍: {{ intro }}</div>
</template>
</Child>
v-slot:abc="{ asdf, intro }"
v-slot 是插槽的指令
:abc是具名插槽的名称,也就是在slot标签上的name属性
="{ asdf, intro }" 等号里面的对象是解构,解构绑定在slot标签上的属性
注意:
v-slot 指令可以简写成 #
v-slot:qwer="{ userinfo, intro }"
#qwer="{ userinfo, intro }"
如果是默认插槽的话,#default="" default不能省略