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

uni-app学习笔记十三-vue3中slot插槽的使用

在页面开发中,通常一个页面分为头部,尾部,和中心内容区。其中头部,尾部一般比较固定,而中心区域往往是多样的,需要自定义开发。此时,我们可以引入slot(插槽)来实现这一目标。<slot> 作为一个占位符,父组件传递进来的内容就会渲染在这里。

下面使用slot来实现2个页面中心区域的差异化开发:

项目结构如下:

1.在项目组件components文件夹里新建一个组件:xxy-layout,在xxy-layout.vue文件写入下面的代码:

<template><view class="layout"><view class="header">header区</view><view class="main"><slot></slot></view><view class="footer">底部区</view></view>
</template><script setup></script><style lang="scss" scoped>.layout{.header{height: 100px;background: #cfcfcf;}.main{min-height: 200px;}.footer{height: 120px;background: orange;}}
</style>

 2.在demo1和demo2分别引入xxy-layout组件

demo1:

<template><view><xxy-layout><view class="row" v-for="item in 10">每一行{{item}}</view></xxy-layout></view>
</template>

demo2:

<template><view><xxy-layout><view class="box1"></view><view class="box2"></view></xxy-layout></view>
</template><script setup></script><style lang="scss" scoped>.box1{width: 100px;height: 100px;background: yellowgreen;}.box2{width: 100px;height: 100px;background: yellow;}
</style>

 从而实现中心区域的差异化

如果一个页面多处需要用到slot,就需要用到具名插槽。此时demo1和demo2还像上面写,将会失效。对上面xxy-layout.vue进行调整,分别在header和main引入slot,此时需要添加name以示区分。

<view class="header"><slot name="header"></slot>
</view>
<view class="main"><slot name="main"></slot>
</view>

此时再来看页面,中间的内容消失了,demo2也是一样。

因此使用具名插槽后,需要对引入子组件部分进行调整,

方法1:通过template v-slot来实现

<xxy-layout><template v-slot:header>demo1头部</template><template v-slot:main>demo1中心区</template>
</xxy-layout>

效果:

方法2:使用#插槽名称

<xxy-layout><template #header>demo2头部</template><template #main>demo2中心区</template>
</xxy-layout>

效果:

http://www.xdnf.cn/news/8770.html

相关文章:

  • 2025年开发者生存白皮书
  • 中断和信号详解
  • 前端课设Web2
  • MySQL中简单的操作
  • day36 python神经网络训练
  • AI助力,制作视频裁剪软件
  • 达梦数据库-学习-23-获取执行计划的N种方法
  • UE C++学习笔记之创建组件
  • 精选19道SQL面试题:覆盖查询、概念与常见陷阱
  • 前端开发知识体系全景解析
  • GO 语言基础3 struct 结构体
  • GO 语言进阶之 Template 模板使用
  • 使用中文作为map的可以,需要注意什么
  • linux学习第15天(递归遍历目录实现-ls -R)
  • 【C语言练习】062. 使用位运算优化算法
  • Lua基础语法
  • Linux 内核学习(9) --- Linux sysfs 文件系统
  • 【Redis】浅谈分布式系统
  • libevent2-介绍
  • 深入理解 JavaScript 面向对象编程与 Class
  • EPD_2IN7_V2_Clear() 和 Paint_Clear(WHITE) 的区别
  • 深度解析视频剪辑SDK开发:从AI字幕提取到多端原生插件集成-优雅草卓伊凡
  • 小白的进阶之路系列之四----人工智能从初步到精通pytorch自定义数据集上
  • Hertz+Kitex快速上手开发
  • 学习日志12 java
  • 低功耗蓝牙BLE之LE Controller Package CRC校验
  • MySQL 定时逻辑备份
  • uni-app学习笔记十二-vue3中组件传值(属性传值)
  • 解决DeepSeek部署难题:提升效率与稳定性的关键策略
  • 《JavaScript 性能优化:从原理到实战的全面指南》