vue中有三种插槽:普通插槽,具名插槽,作用域插槽
普通插槽:就是放在子组件的一个站位:
父组件代码:
<div class='father'>
<div>我是父组件</div>
<son>
<div>
这是普通插槽
</div>
</son>
</div>
子组件代码:需要在子组件添加<slot></slot>进行站位,不然不展示
<template>
<div class=''>
<div>我是子组件</div>
<!-- 普通插槽站位 -->
<slot></slot>
</div>
</template>
效果:
具名插槽:给内容添加名字:
先父组件:slot="header",定义好名字,子组件接收
<template slot="header">
<div class="fatherBox1">头部内容</div>
</template>
<template>
<div class='father'>
<div class="fatherBox">我是父组件</div>
<son>
<template slot="header">
<div class="fatherBox1">头部内容</div>
</template>
<template slot="footer">
<div class="fatherBox1">底部内容</div>
</template>
</son>
</div>
</template>
子组件接收数据:name="header",这里的name对应父组件定义的名字
<slot name="header"></slot>
<template>
<div class=''>
<div>我是子组件</div>
<!-- 具名插槽 -->
<slot name="header"></slot>
<slot name="footer"></slot>
</div>
</template>
效果:
作用域插槽:
可以拿到子主件传递给父组件的数据,是一个对象数据
父组件:#header="scope"中header对应子组件插槽名字,传递的可以是任意类型,但是scope是一个对象
<template #header="scope">
<div class="fatherBox1">数组:{{scope}}</div>
</template>
<template>
<div class='father'>
<div class="fatherBox">我是父组件</div>
<son>
<template #header="scope">
<div class="fatherBox1">数组:{{scope}}</div>
</template>
<template #footer="scope">
<div class="fatherBox1">对象:{{scope}}</div>
</template>
</son>
</div>
</template>
<script>
import son from "./son.vue";
export default {
components: {
son,
},
};
子主件: header定义的名字让父组件接收,:arr='arr'是传递数据给父组件
<slot name="header" :arr='arr'></slot>
<template>
<div class=''>
<div>我是子组件</div>
<!-- 作用域插槽 -->
<slot name="header" :arr='arr'></slot>
<slot name="footer" :obj='obj'></slot>
</div>
</template>
<script>
export default {
data() {
return {
arr: [1, 2, 3, 4, 5],
obj:{
name:'貂蟬',
age:18,
sex:'女'
}
};
},
};
</script>
效果: