在调用子组件时,我们希望把父组件的HTML传给子组件,那么在引用子组件内部进行定义,然后子组件通过slot标签进行接收
基本示例
父 app.vue
<!--内容控制-->
<template><test><div><p>{{name}}</p><p>{{age}}</p></div></test></template>
<!--JS 控制-->
<script>import test from "@/components/test.vue";export default {components: {test},data() {return {name: '李四',age: 100}}}
</script>
子 test.vue
<template><div><p>测试插槽:</p><slot></slot></div>
</template>
<script setup lang="ts">
</script>
自定义插槽
有时我们并不需要把相关需要的信息全部传过去或者需要根据条件进行局部显示,那么需要通过<template v-slot:命名>(也可以#命名)定义插槽进行命名,然后插槽时指定<slot name="命名"></slot>来实现。
父 app.vue
<!--内容控制-->
<template><test><template v-slot:ProName><div><p>{{name}}</p></div></template><!-- 也可以如下命名 --><template #ProAge><div><p>{{age}}</p></div></template></test></template>
<!--JS 控制-->
<script>import test from "@/components/test.vue";export default {components: {test},data() {return {name: '李四',age: 100}}}
</script>
子 test.vue
<template><div><p>测试插槽:</p><slot name="ProName"></slot><br><slot name="ProAge"></slot></div>
</template>
子组件反向对父组件进行传值
有时我们会需要把子组件的数据要传回给父组件(反向传值),子组件绑定并值并命名,
父组件通过v-slot="命名"的接收。
子 test.vue
<template><div><p>测试插槽:</p><slot name="ProName"></slot><br><slot name="ProAge"></slot><br><slot :msg="sex"></slot><slot name="ProBthDay" :BthDay="BthDay"></slot></div>
</template>
<script >
export default {data() {return {sex: '男',BthDay: '1999-01-01'}}
}
</script>
父 app.vue
<!--内容控制-->
<template><test><template v-slot:ProName><div><p>{{name}}</p></div></template><!-- 也可以如下命名 --><template #ProAge><div><p>{{age}}</p></div></template><template v-slot="ProSex" ><div><p>接收到:{{ProSex.msg}}</p></div></template><template #ProBthDay ="ProBthDay" ><div><p>接收到:{{ProBthDay.BthDay}}</p></div></template></test></template>
<!--JS 控制-->
<script>import test from "@/components/test.vue";export default {components: {test},data() {return {name: '李四',age: 100}}}
</script>