一、插槽插槽就是子组件中的提供给父组件使用的一个占位符,用<slot></slot> 表示,父组件可以在这个占位符中填充任何模板代码,如 HTML、组件等,填充的内容会替换子组件的<slot></slot>标签。
二、具名插槽描述:具名插槽其实就是给插槽娶个名字。一个子组件可以放多个插槽,而且可以放在不同的地方,而父组件填充内容时,可以根据这个名字把内容填充到对应插槽中。
三、 默认插槽
描述: 默认插槽就是指没有名字的插槽,子组件未定义的名字的插槽,父级将会把 未指定插槽的填充的内容填充到默认插槽中。
四、作用域插槽
作用域插槽就是带数据的插槽
父组件:
<template>
<div class="father">
<h3>这里是父组件</h3>
<!--第一次使用:用flex展示数据-->
<child>
<template v-slot="user">
<div class="tmpl">
<span v-for="item in user.data" :key="item.index">{{item}}</span>
</div>
</template>
</child>
<!--第二次使用:用列表展示数据-->
<child>
<template v-slot="user">
<ul>
<li v-for="item in user.data" :key="item.index">{{item}}</li>
</ul>
</template>
</child>
<!--第三次使用:直接显示数据-->
<child>
<template v-slot="user">{{user.data}}</template>
</child>
<!--第四次使用:不使用其提供的数据, 作用域插槽退变成匿名插槽-->
<child>我就是模板</child>
</div>
</template>
<script>
import child from "@/components/SlotChild"
export default {
name: "vueName",
data() {
return {
msg: "Welcome to your vueName",
};
},
components:{
child
}
};
</script>
<style scoped lang = "less">
</style>
子组件:
<template>
<div class="slotChild">
<div class="child">
<h3>这里是子组件</h3>
<slot :data="data"></slot>
</div>
</div>
</template>
<script>
export default {
name: "vueName",
data() {
return {
data: ["zhangsan", "lisi", "wanwu", "zhaoliu", "tianqi", "xiaoba"],
};
},
};
</script>
<style scoped lang = "less">
</style>
1、
父组件如果需要往子组件中填充模板或者html,会覆盖
必须在
子组件中写入插槽
(类似于
父传子)
2、注意:
1. 父级的填充内容如果指定到子组件的没有对应名字插槽,那么该内容不会被填充到默认插槽中。
2. 如果子组件没有默认插槽,而父级的填充内容指定到默认插槽中,那么该内容就“不会”填充到子组件的任何一个插槽中。
3. 如果子组件有多个默认插槽,而父组件所有指定到默认插槽的填充内容,将“会” “全都”填充到子组件的每个默认插槽中。
原文链接: