匿名插槽/单个插槽/默认插槽
单个插槽可以放在一个组件的任意位置,且没有name值。一个组件只能有一个匿名插槽。
父组件:
<template>
<div class="father">
<h3>这里是父组件</h3>
<child>
<div class="tmpl">
<span>item1</span>
<span>item2</span>
</div>
</child>
</div>
</template>
子组件
<template>
<div class="child">
<h3>这里是子组件</h3>
<slot></slot>
</div>
</template>
子组件上的slot会被父组件child里面的html元素给替换掉。
具名插槽
具名插槽新增了一个name属性,使得一个具名插槽可以再组件中出现多次。出现在不同的位置。
父组件:
<template>
<div class="father">
<h3>这里是父组件</h3>
<child>
<div slot='header' class="tmpl">
<span>item1---1</span>
<span>item2---1</span>
</div>
<div slot='footer' class="tmpl">
<span>item3---1</span>
<span>item4---1</span>
</div>
<p>
匿名插槽的模板
</p>
</child>
</div>
</template>
子组件
<template>
// 具名插槽
<slot name="header"></slot>
// 具名插槽
<slot name="footer"></slot>
// 匿名插槽
<slot></slot>
<template>
在父组件中
- 有slot属性的关联子组件的具名插槽
- 没有slot属性的关联子组件的匿名插槽
作用域插槽/带数据的插槽
作用域插槽要求,在slot上面绑定数据,或者在组件模板template上面绑定:data
在组件模板之中可以使用作用域插槽slot-scope="scope"
来取得该作用域插槽:data绑定的数据
scope的名字可以随意改变,只是定义对象来代表取得data的数据。
主要看父组件有没有写组件模板
父组件:
<template>
<div class="father">
<h3>这里是父组件</h3>
<!--第一次使用:用flex展示数据-->
<child>
<template slot-scope="user">
<div class="tmpl">
<span v-for="item in user.data">{{item}}</span>
</div>
</template>
</child>
<!--第二次使用:用列表展示数据-->
<child>
<template slot-scope="user">
<ul>
<li v-for="item in user.data">{{item}}</li>
</ul>
</template>
</child>
<!--第三次使用:直接显示数据-->
<child>
<template slot-scope="user">
{{user.data}}
</template>
</child>
<!--第四次使用:不使用其提供的数据, 作用域插槽退变成匿名插槽-->
<child>
我就是模板
</child>
</div>
</template>
子组件:
<template>
<div class="child">
<h3>这里是子组件</h3>
// 作用域插槽
<slot :data="data"></slot>
</div>
</template>
export default {
data: function(){
return {
data: ['zhangsan','lisi','wanwu','zhaoliu','tianqi','xiaoba']
}
}
}
export default {
data: function(){
return {
data: [‘zhangsan’,‘lisi’,‘wanwu’,‘zhaoliu’,‘tianqi’,‘xiaoba’]
}
}
}
![img](https://img-blog.csdnimg.cn/img_convert/59136a4af21acd01122cc083ebd55205.png)