当前位置: 首页 > news >正文

前端流行框架Vue3教程:21. 插槽(3)

21. 插槽(3)

在某些场景下插槽的内容可能想要同时使用父组件域内和子组件域内的数据。要做到这一点,我们需要一种方法来让子组件在渲染时将一部分数据提供给插槽。
我们也确实有办法这么做!可以像对组件传递props那样,向一个插槽的出口上传递attributes

SlotsAttr.vue

<script>
/*** 定义一个Vue组件* 该组件包含一个名为childMessage的数据属性,用于传递信息到子组件*/
export default {data() {// 初始化组件的数据属性return {childMessage: '子组件数据'}}
}
</script><template><!-- 组件标题 --><h3>Slots3</h3><!-- 定义一个插槽,并传递childMessage数据属性给子组件 --><slot :msg="childMessage"></slot>
</template>

App.vue

<script>
// 导入SlotsAttr组件,用于展示插槽内容
import SlotsAttr from "@/components/SlotsAttr.vue";// 定义当前组件的导出对象
export default {// 注册组件components: {SlotsAttr},// 定义数据属性data() {return {// 当前测试内容currentTest: "测试内容"}}
}
</script><template><!-- 使用SlotsAttr组件,并通过v-slot指令定义默认插槽的内容 --><SlotsAttr v-slot="slotProps"><!-- 展示来自组件内部的数据 --><h3>{{ currentTest }}</h3><!-- 展示来自SlotsAttr组件传递的msg属性 --><h3>{{ slotProps.msg }}</h3></SlotsAttr>
</template>

具名插槽传递数据

SlotsAttr.vue

<script>
export default {data() {// 初始化组件的数据属性return {childMessage: '具名子组件数据',jobMessage: '程序员'}}
}
</script><template><h3>Slots3</h3><slot name="header" :msg="childMessage"></slot><slot name="main" :job="jobMessage"></slot>
</template>

App.vue

<script>import SlotsAttr from "@/components/SlotsAttr.vue";export default {components: {SlotsAttr},data() {}
}
</script><template><SlotsAttr><template #header="slotProps"><h3>{{ slotProps.msg }}</h3></template><template #main="slotProps"><p>{{ slotProps.job }}</p></template></SlotsAttr>
</template>

相关文章:

  • C语言| 指针变量的初始化
  • 如何测试北斗卫星通讯终端的性能?
  • DEBUG:Lombok 失效
  • C++类与对象--6 特性二:继承
  • std::vector<>.emplace_back
  • flutter设置最大高度,超过最大高度时滑动显示
  • 使用frp内网穿透本地的虚拟机
  • spring event事件(四)内部事件(1)ApplicationReadyEvent
  • 介绍Buildroot
  • 2025ICPC南昌邀请赛题解
  • 记录学习的第三十六天
  • ZYNQ Cache一致性问题解析与实战:从原理到创新优化
  • PEFT简介及微调大模型DeepSeek-R1-Distill-Qwen-1.5B
  • mysql不能聚合之数据清洗逗号
  • 第7天-Python+PyEcharts实现股票分时图实战教程
  • OD 算法题 B卷 【需要打开多少监视器】
  • 算法打卡第一天
  • 每日算法刷题Day10 5.19:leetcode不定长滑动窗口求最长/最大4道题,结束定长滑动窗口,用时1h
  • 大模型的开发应用(三):基于LlaMAFactory的LoRA微调(上)
  • CSS之box-sizing、图片模糊、计算盒子宽度clac、(重点含小米、进度条案例)过渡
  • wordpress无法正常显示图片/网络公司seo推广
  • 贵州省建设监理协会官方网站/百度纯净版首页入口
  • 恩施网站建设模板/全网网络营销推广
  • 龙湾做网站/百度关键词购买
  • pc端和手机端网站建设/便宜的seo网络营销推广
  • wordpress网站打不开/seo查询官方网站