欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 幼教 > vue3 学习笔记12 -- 插槽的使用

vue3 学习笔记12 -- 插槽的使用

2024/10/25 7:20:28 来源:https://blog.csdn.net/weixin_46328739/article/details/140468097  浏览:    关键词:vue3 学习笔记12 -- 插槽的使用

vue3 学习笔记12 – 插槽的使用

插槽(Slots)是一种让父组件能够向子组件传递标记的方法。通过定义插槽,子组件可以预留出可由父组件控制的区域,这样父组件就可以向这些区域填充自己的内容。

假设我们有一个父组件 ParentComponent 和一个子组件 ChildComponent

默认插槽(Default Slot)

默认插槽是最基本的插槽形式,允许父组件在子组件中插入任意内容,而子组件则可以通过 来渲染这些内容。

  • ParentComponent.vue
<template><div><h2>Parent Component</h2><ChildComponent><!-- 这里是默认插槽 --><p>Content inside parent component</p></ChildComponent></div>
</template><script setup lang="ts">
import ChildComponent from './ChildComponent.vue';
</script>
  • ChildComponent.vue
<template><div><h3>Child Component</h3><slot></slot></div>
</template><script setup lang="ts">
// TypeScript setup syntax
</script>
  • 上述例子
    • ParentComponent 包含了 ChildComponent,并传递了一些内容作为默认插槽。
    • ChildComponent 中使用了 来显示来自父组件的内容。

具名插槽(Named Slots)

具名插槽允许父组件在子组件中定义多个插槽位置,使得父组件可以将不同的内容分发到不同的插槽中。这种方式特别适合需要布局或者结构化控制的场景。

  • ParentComponent.vue
<template><div><h2>Parent Component</h2><ChildComponent><!-- 具名插槽 --><template #header><h3>Header in Parent</h3></template><template #footer><p>Footer in Parent</p></template></ChildComponent></div>
</template><script setup lang="ts">
import ChildComponent from './ChildComponent.vue';
</script>
  • ChildComponent.vue
<template><div><h3>Child Component</h3><slot name="header"></slot><slot name="footer"></slot></div>
</template><script setup lang="ts">
// TypeScript setup syntax
</script>
  • 上述例子
    • ParentComponent 通过使用 <template #header> 和 <template #footer> 来定义具名插槽的内容
    • ChildComponent 中使用了 和 来渲染具名插槽的内容。

作用域插槽

子组件向父组件传递数据的一种形式,子组件在具名标签或者匿名标签上绑定数据,父组件在标签上获取数据

  • ParentComponent.vue
<template><div><ChildComponent v-slot="{ text,count }"><div>{{ text }}---{{ count }}</div></ChildComponent></div>
</template><script setup lang="ts">
import ChildComponent from './ChildComponent.vue';const message = 'Hello from Parent';
</script>
  • ChildComponent.vue
<template><div><p>我是子组件</p><slot text="我是子组件" :count="1"></slot></div>
</template>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com