一.slot
插槽,也就是slot,是组件的一块HTML模板,这块模板显示不显示、以及怎样显示由父组件来决定。值得注意的是:内容要写在父组件中,然后分给需要的子组件,当slot多个时,可以通过name来加以区分,这就是所谓的具名插槽。
举个例子
父组件:
<template>
<div>
<h3>这是父组件</h3>
<son><span>实践slot</span></son>
<son>
<template slot="myslot">
<div>
实践具名slot
</div>
</template>
</son>
</div>
</template>
子组件:
<template>
<div>
<h4>这是子组件</h4>
<input type="text" placeholder="请输入">
<slot></slot>
<slot name="myslot"></slot>
</div>
</template>
效果:
二.slot-scope
slot-scope就是作用域插槽。官方叫它作用域插槽,实际上,对比具名插槽,我们可以叫它带数据的插槽。具名插槽在组件的template里面写,作用域插槽要求,在slot上面绑定数据。
举个例子
父组件:
<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']
}
}
}
效果: