插槽显不显示、怎样显示是由父组件来控制的,而插槽在哪里显示就由子组件来进行控制
父组件
<template>
<div>
<!-- 默认显示子组件 -->
<student :stu="stu"></student>
<!-- 子组件显示内容有父组件决定 -->
<student :stu="stu">
<template slot-scope="slotProps">
{{ slotProps.slotData.name }}
</template>
</student>
<student :stu="stu">
<template slot-scope="slotProps">
{{ slotProps.slotData.gender }}
</template>
</student>
<student :stu="stu">
<template slot-scope="slotProps">
{{ slotProps.slotData.address }}
</template>
</student>
</div>
</template>
<script>
import student from "../../components/student";
export default {
components: {
student,
},
data() {
return {
stu: { name: "张三", gender: "男", address: "苏州" },
};
},
};
</script>
子组件
<template>
<span>
<!-- 子组件定义插槽 -->
<slot :slotData="stu">
<!-- 默认值显示 name ,即父组件不传内容时 -->
{{ stu.name }}
</slot>
</span>
</template>
<script>
export default {
name: "student",
props: {
stu: { name: "", gender: "", address: "" },
},
data() {
return {};
},
};
</script>
|