一、为什么使用
在子组件中默认显示内容 {{bookinfo.title}},父组件不传值,则显示 {{bookinfo.title}}
// 子组件:Testslot.vue
<template>
<div>
<!-- 插槽 prop -->
<slot name="slotName" :info="bookinfo">{{bookinfo.title}}</slot>
</div>
</template>
<script>
export default {
data() {
return {
bookinfo: {
title: '三体',
descriptioin: '科幻著作'
}
};
}
};
</script>
如果想通过父组件来控制子组件的显示,想显示 {{bookinfo.descriptioin}},直接使用是不行的,因为父组件并不能直接获取子组件的内容
// 父组件
// 这样写会报错
<template v-slot:slotNam>
{info.descriptioin}}
</template>
二、而要想获取子组件的内容,选择性的展示,就要通过作用域插槽,整个过程分两步走
1、在子组件的 slot 标签上,绑定你要传给父组件的数据,就像 Prop 的语法一样
// 子组件:Testslot.vue
<template>
<div>
<!-- 这里 info 就是要传给父组件的 prop 变量,bookinfo 就是实际的内容 -->
<slot name="slotName" :info="bookinfo">{{bookinfo.title}}</slot>
</div>
</template>
<script>
export default {
data() {
return {
bookinfo: {
title: '三体',
descriptioin: '科幻著作'
}
}
}
}
</script>
2、在父组件中定义一个参数,通过该参数来获取传入的数据
<!-- 这里我用 receiver 来接收这个 info 的数据,slotName 是这个具名插槽的名 -->
<template v-slot:slotName="receiver">
{{receiver.info.descriptioin}}
</template>
简写
// 简写
// receiver 只是用于接收 info 的临时值,你可以直接用解构的方式来获取 info
<template v-slot:slotName="{info}">
{{info.descriptioin}}
</template>