完成首页精品微课、订阅专栏等关联组件
在 vp-card 和 vp-item 基础组件就绪后,本节将它们组合为首页的业务区域:为你推荐、精品微课、学习计划和订阅专栏。核心思路是识别不同区域的共性结构,通过 props 和 slot 实现差异化展示。
为你推荐(横向滚动)
结构
<template>
<vp-card title="为你推荐" :wrapClass="'p-x-2'">
<scroll-view scroll-x class="whitespace-nowrap">
<view class="inline-flex flex-col items-start mr-3">
<vp-item image="..." width="120rpx" height="160rpx" />
<text class="text-xs pl-1 pt-2">科技专题</text>
</view>
<!-- 复制多个 -->
</scroll-view>
</vp-card>
</template>
vue
关键点
- 使用
scroll-view组件的scroll-x属性实现横向滚动 - 外层
whitespace-nowrap防止换行 - 每个 item 使用
inline-flex实现内联布局 mr-3控制 item 之间的间距
精品微课(左图右文列表)
结构
<template>
<vp-card title="精品微课" :wrapClass="'p-y-2'">
<view class="flex mr-4">
<!-- 左侧图片 -->
<vp-item image="..." width="200rpx" height="150rpx" />
<!-- 右侧信息 -->
<view class="flex flex-col items-start ml-3">
<text class="font-bold mb-2 line-clamp-1">课程标题</text>
<text class="text-gray-400 text-xs mb-2 line-clamp-2">课程描述...</text>
<view class="flex">
<text class="rounded bg-gray-500 text-white py-1 px-2 scale-80 text-xs">标签一</text>
<text class="rounded bg-gray-500 text-white py-1 px-2 scale-80 text-xs">标签二</text>
</view>
</view>
</view>
</vp-card>
</template>
vue
样式细节
| 元素 | 样式 | 说明 |
|---|---|---|
| 标题 | font-bold mb-2 line-clamp-1 | 加粗、单行省略 |
| 描述 | text-gray-400 text-xs mb-2 line-clamp-2 | 灰色小字、两行省略 |
| 标签 | rounded bg-gray-500 text-white py-1 px-2 scale-80 | 圆角灰色背景、白色小字 |
| 整体间距 | mr-4 | item 之间的右间距 |
vp-card 的 wrapClass 优化
不同区域对 vp-card 的内边距需求不同。为此将 p-4 改为可配置的 wrapClass:
<!-- vp-card 组件 -->
<script setup>
defineProps({
title: { type: String, default: '' },
wrapClass: { type: String, default: 'p-4' }
})
</script>
<template>
<view>
<view class="flex justify-between items-center px-4">
<text class="font-bold text-xl">{{ title }}</text>
</view>
<view :class="wrapClass">
<slot />
</view>
</view>
</template>
vue
使用时传入不同的值:
<vp-card title="为你推荐" wrapClass="p-x-2" />
<vp-card title="精品微课" wrapClass="p-y-2" />
<vp-card title="学习计划" wrapClass="p-4" />
vue
自定义样式冲突
如果之前在全局 CSS 中定义了 .flex 样式,可能与 UnoCSS 的 flex class 冲突。解决方法:
- 注释掉全局自定义的
.flex样式 - 统一使用 UnoCSS 的原子化 class
学习计划(四宫格)
学习计划使用 grid 布局:
<vp-card title="学习计划">
<view class="grid grid-cols-2 gap-3">
<view v-for="item in plans" :key="item.id">
<vp-item :image="item.image" />
<text>{{ item.name }}</text>
</view>
</view>
</vp-card>
vue
订阅专栏
与精品微课结构相同,也是左图右文的列表布局,可以直接复用相同的结构。
组件复用总结
| 区域 | 使用的基础组件 | 特殊处理 |
|---|---|---|
| 为你推荐 | vp-card + vp-item | scroll-view 横向滚动 |
| 精品微课 | vp-card + vp-item | 左图右文 flex 布局 |
| 学习计划 | vp-card + vp-item | grid 宫格布局 |
| 订阅专栏 | vp-card + vp-item | 同精品微课 |
| 大家都在学 | vp-card + vp-course-item | grid + 课程卡片 |
↑