vue3默认插槽、具名插槽以及作用域插槽实现父子组件通信

默认插槽与具名插槽

父组件

<template><div><h1>我是父组件</h1><child><div style="color: red">我是从父元素插入的值(默认插槽)</div><template #juming><div style="color: green">我是从父元素插入的值(具名插槽)</div></template></child></div>
</template><script setup>
import child from './child.vue'
</script>

子组件

<template><div><hr /><h3>我是子组件</h3><hr /><h5>默认插槽</h5><div><slot></slot></div><hr><h5>具名插槽</h5><slot name="juming"></slot></div>
</template><script setup>
import slot from './slot.vue'
</script>

在这里插入图片描述

作用域插槽

父元素

<template><div><h1>我是父组件</h1><child><template v-slot="{$num}"><div>父元素获取到的子元素的值:{{ $num }}</div></template></child></div>
</template><script setup>
import child from './child.vue'
</script>

子元素

<template><div><hr /><h3>我是子组件</h3><hr /><h5>作用域插槽</h5><slot :$num="num"></slot></div>
</template><script setup>
import { ref } from 'vue'
import slot from './slot.vue'
let num = ref(520)
</script>

在这里插入图片描述