hookehuyr

feat(article): 文章模块功能开发

- 新增 ArticleCard 组件,支持可配置封面图显示 (showCover prop)
- 新增文章详情页 (article-detail)
- 新增文章收藏页 (article-favorites)
- 优化分类列表页 (category-list) 支持混合渲染模式:
  * max_depth > 1: 显示二级分类卡片 (SectionCard)
  * max_depth === 1: 直接显示文章列表 (ArticleCard)
- 过滤空状态项 (max_depth === 1 且 list 为空)
- 统一样式规范:标题区域使用渐变背景,内容区域增加间距

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This diff is collapsed. Click to expand it.
1. 把以前的文档列表接口换成了文章列表接口. 就是把接口a: file, t: file_list 改成 a:article, t:list, 改成文章列表的主要改动点在list字段的结构, 原来的list字段是一个文件列表, 现在变成了文章列表.根据新的list字段改造列表显示卡片的显示和逻辑.
post_link 外部链接字段暂时不要使用,因为没有web-view的功能, 以后有需求再考虑.
2. 新增文章详情页面,有新增文章详情接口, 你先根据后端字段规划页面结构和逻辑生成计划, 不急着生成页面.post_link 外部链接字段暂时不要使用,因为没有web-view的功能, 以后有需求再考虑.
3. 新增文章收藏列表的页面,有新增文章收藏列表接口, 现在我的页面里面有个我的收藏项, 暂时先再配置上屏蔽,新增一个叫我的收藏文章的列表项目, 点击显示用户收藏的文章列表.页面的样式和查询逻辑和原来的收藏列表页面保持一致.post_link 外部链接字段暂时不要使用,因为没有web-view的功能, 以后有需求再考虑.
4. 本周热门资料接口要改掉,改成热门文章接口,等于就是改接口名称, list字段内容可能要重新适配,post_link 外部链接字段暂时不要使用,因为没有web-view的功能, 以后有需求再考虑.
<template>
<view class="flex flex-row bg-white rounded-[24rpx] p-[24rpx] shadow-sm border border-gray-100 article-card" @tap="handleCardClick">
<!-- 左侧封面图 -->
<view v-if="showCover" class="w-[160rpx] h-[120rpx] mr-[24rpx] flex-shrink-0 rounded-[16rpx] overflow-hidden bg-gray-100 self-start">
<image
v-if="coverUrl"
:src="coverUrl"
class="w-full h-full"
mode="aspectFill"
/>
<view v-else class="w-full h-full flex items-center justify-center bg-gradient-to-br from-blue-50 to-blue-100">
<text class="text-gray-400 text-[40rpx]">📄</text>
</view>
</view>
<!-- 内容区域 -->
<view class="flex-1 min-w-0">
<!-- 标题 -->
<view class="text-[#1F2937] text-[30rpx] font-bold leading-[1.4] mb-[8rpx] line-clamp-2">
{{ title }}
</view>
<!-- 简介 -->
<view v-if="excerpt" class="text-[#6B7280] text-[24rpx] leading-[1.4] mb-[8rpx] line-clamp-1">
{{ excerpt }}
</view>
<!-- 元信息:日期 + 学习人数 -->
<view class="flex items-center gap-[12rpx] mb-[16rpx]">
<view class="text-[#9CA3AF] text-[22rpx]">
📅 {{ formattedDate }}
</view>
<!-- 学习人数 -->
<view v-if="learners" class="inline-flex items-center justify-center px-[8rpx] py-[2rpx] bg-orange-50 text-orange-600 text-[20rpx] font-medium rounded-[6rpx]">
<text>{{ learners }}人学习</text>
</view>
<!-- 热度百分比 -->
<view v-if="readPeoplePercent !== undefined && readPeoplePercent !== null" class="inline-flex items-center justify-center px-[8rpx] py-[2rpx] bg-green-50 text-green-600 text-[20rpx] font-medium rounded-[6rpx]">
<text>{{ readPeoplePercent }}%热度</text>
</view>
</view>
<!-- 分割线 -->
<view class="h-[1rpx] bg-gray-100 my-[20rpx]"></view>
<!-- 操作按钮 -->
<ListItemActions
:viewable="true"
:collectable="true"
:deletable="false"
:collected="collected"
:item-id="String(id)"
@view="handleView"
@collect="handleCollect"
/>
</view>
</view>
</template>
<script setup>
/**
* 文章卡片组件
*
* @description 文章列表项卡片,展示封面图、标题、简介、日期和操作按钮
* @component ArticleCard
*/
import { defineProps, defineEmits, computed } from 'vue';
import { useGo } from '@/hooks/useGo';
import ListItemActions from '@/components/list/ListItemActions/index.vue';
import { useCollectOperation } from '@/composables/useCollectOperation';
import dayjs from 'dayjs';
/**
* 组件属性
*/
const props = defineProps({
/** 文章 ID */
id: {
type: [Number, String],
required: true
},
/** 文章标题 */
title: {
type: String,
required: true
},
/** 文章简介 */
excerpt: {
type: String,
default: ''
},
/** 封面图 URL */
coverUrl: {
type: String,
default: ''
},
/** 发布日期(格式:YYYY-MM-DD HH:mm:ss) */
date: {
type: String,
default: ''
},
/** 学习人数文本 */
learners: {
type: [String, Number],
default: ''
},
/** 学习人数百分比(热度) */
readPeoplePercent: {
type: Number,
default: null
},
/** 是否已收藏 */
collected: {
type: Boolean,
default: false
},
/** 是否显示封面图 */
showCover: {
type: Boolean,
default: true
}
});
/**
* 组件事件
*/
const emit = defineEmits(['viewed', 'collectChanged']);
const go = useGo();
/**
* 格式化日期显示
*
* @description 将 2025-08-19 06:25:46 格式化为 08-19
* @returns {string} 格式化后的日期
*/
const formattedDate = computed(() => {
if (!props.date) return '';
try {
return dayjs(props.date).format('MM-DD');
} catch {
return props.date;
}
});
/**
* 使用收藏操作 composable
*/
const { toggleCollect } = useCollectOperation();
/**
* 处理卡片点击
*
* @description 跳转到文章详情页
*/
const handleCardClick = () => {
go('/pages/article-detail/index', { id: props.id });
};
/**
* 处理查看点击
*
* @description 跳转到文章详情页
*/
const handleView = () => {
handleCardClick();
// 通知父组件查看完成
emit('viewed', { id: props.id });
};
/**
* 处理收藏点击
*
* @description 调用收藏操作并通知父组件
*/
const handleCollect = () => {
// 调用收藏操作
toggleCollect({
id: props.id,
title: props.title,
excerpt: props.excerpt,
coverUrl: props.coverUrl,
date: props.date,
collected: props.collected
});
// 通知父组件收藏状态改变
emit('collectChanged', {
id: props.id,
title: props.title,
excerpt: props.excerpt,
coverUrl: props.coverUrl,
date: props.date,
collected: !props.collected // 新状态(取反)
});
};
</script>
<style lang="less" scoped>
.article-card {
transition: all 0.2s ease;
&:active {
transform: scale(0.98);
background-color: #F9FAFB;
}
// 多行文本省略
.line-clamp-1 {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 1;
line-clamp: 1;
overflow: hidden;
word-break: break-all;
}
.line-clamp-2 {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
line-clamp: 2;
overflow: hidden;
word-break: break-all;
}
}
</style>
export default definePageConfig({
navigationBarTitleText: '文章详情',
backgroundColor: '#F9FAFB',
navigationStyle: 'custom'
})
<!--
* @Date: 2026-02-27
* @Description: 文章详情页
-->
<template>
<view class="article-detail-page">
<!-- 导航栏 -->
<NavHeader title="文章详情" />
<!-- 滚动容器 -->
<view class="flex-1 pb-safe">
<!-- 加载状态 - 自定义 Tailwind CSS 加载动画 -->
<view v-if="loading" class="flex items-center justify-center h-screen">
<view class="flex flex-col items-center">
<view class="w-[64rpx] h-[64rpx] border-4 border-gray-200 border-t-blue-600 rounded-full animate-spin mb-[24rpx]"></view>
<text class="text-gray-600 text-[28rpx]">加载中...</text>
</view>
</view>
<!-- 文章内容 -->
<view v-else-if="article" class="article-content">
<!-- 封面图 -->
<view v-if="article.coverUrl" class="cover-image-wrapper">
<image :src="article.coverUrl" mode="widthFix" class="cover-image" />
</view>
<!-- 文章信息 -->
<view class="article-info px-[32rpx]">
<!-- 标题 -->
<view class="article-title">{{ article.title }}</view>
<!-- 作者和日期 -->
<view class="article-meta">
<text v-if="article.authorName" class="meta-item">{{ article.authorName }}</text>
<text v-if="article.authorName && article.date" class="meta-separator">·</text>
<text v-if="article.date" class="meta-item">{{ formattedDate }}</text>
</view>
</view>
<!-- 分割线 -->
<view class="divider"></view>
<!-- 富文本内容 -->
<view class="article-body px-[32rpx]">
<rich-text :nodes="processedContent" class="rich-text-content" />
</view>
</view>
<!-- 加载失败 - 自定义空状态 -->
<view v-else-if="error" class="error-state">
<view class="flex flex-col items-center justify-center h-screen">
<view class="text-[#9CA3AF] text-[120rpx] mb-[24rpx]">⚠️</view>
<text class="text-gray-600 text-[28rpx] mb-[32rpx]">加载失败</text>
<view
class="px-[48rpx] py-[20rpx] bg-blue-600 text-white rounded-full"
@tap="fetchArticleDetail"
>
<text class="text-[28rpx]">重试</text>
</view>
</view>
</view>
<!-- 底部安全区域 -->
<view class="safe-area-bottom"></view>
</view>
<!-- 底部收藏按钮 -->
<view class="footer-bar">
<view class="footer-content">
<view
v-if="article"
:class="['collect-button', article.is_favorite ? 'collected' : '']"
@tap="toggleCollect"
>
<text class="collect-icon">{{ article.is_favorite ? '★' : '☆' }}</text>
<text class="collect-text">{{ article.is_favorite ? '已收藏' : '收藏' }}</text>
</view>
</view>
</view>
</view>
</template>
<script setup>
import { ref, computed } from 'vue'
import { useLoad } from '@tarojs/taro'
import NavHeader from '@/components/navigation/NavHeader.vue'
import { articleDetailAPI } from '@/api/article'
import { addAPI, delAPI } from '@/api/favorite'
import { mockArticleDetailAPI } from '@/utils/mockData'
import eventBus, { Events } from '@/utils/eventBus'
import dayjs from 'dayjs'
import Taro from '@tarojs/taro'
import { USE_MOCK_DATA } from '@/config/app'
/**
* 文章数据
*/
const article = ref(null)
/**
* 加载状态
*/
const loading = ref(true)
/**
* 错误状态
*/
const error = ref(false)
/**
* 文章 ID
*/
const articleId = ref(null)
/**
* 格式化日期显示
*/
const formattedDate = computed(() => {
if (!article.value?.post_date) return ''
try {
return dayjs(article.value.post_date).format('YYYY年MM月DD日')
} catch {
return article.value.post_date
}
})
/**
* 处理富文本内容,适配图片宽度
*/
const processedContent = computed(() => {
if (!article.value?.content) return ''
// 给 img 标签添加内联样式,确保宽度不超过容器
return article.value.content.replace(/<img/gi, '<img style="max-width:100%;height:auto;display:block;margin:12px auto;"')
})
/**
* 获取文章详情
*/
const fetchArticleDetail = async () => {
if (!articleId.value) return
loading.value = true
error.value = false
try {
console.log('[Article Detail] 获取文章详情:', articleId.value)
console.log('[Article Detail] 使用 Mock 数据:', USE_MOCK_DATA)
const res = USE_MOCK_DATA
? await mockArticleDetailAPI({ i: articleId.value })
: await articleDetailAPI({ i: articleId.value })
if (res.code === 1 && res.data) {
console.log('[Article Detail] 数据:', res.data)
article.value = {
id: res.data.id,
title: res.data.post_title || '未命名文章',
content: res.data.post_content || '',
excerpt: res.data.post_excerpt || '',
coverUrl: res.data.cover_url || res.data.post_thumbnail || '',
date: res.data.post_date || '',
authorName: res.data.author_name || '',
is_favorite: res.data.is_favorite === 1 || res.data.is_favorite === '1'
}
} else {
error.value = true
Taro.showToast({
title: res.msg || '获取文章详情失败',
icon: 'none'
})
}
} catch (err) {
console.error('[Article Detail] 获取文章详情失败:', err)
error.value = true
Taro.showToast({
title: '加载失败',
icon: 'error'
})
} finally {
loading.value = false
}
}
/**
* 切换收藏状态
*/
const toggleCollect = async () => {
if (!article.value) return
try {
const newCollectStatus = !article.value.is_favorite
// 调用收藏 API(使用与文件相同的收藏 API)
const res = newCollectStatus
? await addAPI({ meta_id: article.value.id })
: await delAPI({ meta_id: article.value.id })
if (res.code === 1) {
// 更新本地状态
article.value.is_favorite = newCollectStatus
Taro.showToast({
title: newCollectStatus ? '已收藏' : '已取消收藏',
icon: 'success',
duration: 1000
})
// 发送收藏更新事件
eventBus.emit(Events.FAVORITES_UPDATE, {
metaId: article.value.id,
collected: newCollectStatus,
timestamp: Date.now()
})
} else {
Taro.showToast({
title: res.msg || '操作失败',
icon: 'none',
duration: 2000
})
}
} catch (err) {
console.error('[Article Detail] 收藏操作失败:', err)
Taro.showToast({
title: '网络错误,请重试',
icon: 'none',
duration: 2000
})
}
}
/**
* 滚动到底部事件
*/
const onScrollToLower = () => {
// 可以在这里加载相关文章推荐等
console.log('[Article Detail] 滚动到底部')
}
/**
* 页面加载时获取文章详情
*/
useLoad((options) => {
console.log('[Article Detail] 页面参数:', options)
if (options.id) {
articleId.value = options.id
fetchArticleDetail()
} else {
error.value = true
loading.value = false
Taro.showToast({
title: '文章ID不存在',
icon: 'none'
})
}
})
</script>
<style lang="less">
.article-detail-page {
display: flex;
flex-direction: column;
min-height: 100vh;
background-color: #F9FAFB;
}
.cover-image-wrapper {
width: 100%;
background-color: #F3F4F6;
}
.cover-image {
width: 100%;
display: block;
}
.article-info {
padding-top: 32rpx;
padding-bottom: 24rpx;
}
.article-title {
font-size: 40rpx;
font-weight: bold;
color: #1F2937;
line-height: 1.4;
margin-bottom: 16rpx;
}
.article-meta {
display: flex;
align-items: center;
font-size: 24rpx;
color: #9CA3AF;
}
.meta-item {
margin-right: 8rpx;
}
.meta-separator {
margin-right: 8rpx;
}
.divider {
height: 1rpx;
background-color: #E5E7EB;
margin: 0 0 32rpx 0;
}
.article-body {
padding-bottom: 32rpx;
}
.rich-text-content {
font-size: 30rpx;
color: #374151;
line-height: 1.8;
word-wrap: break-word;
overflow: hidden;
/* 富文本图片样式:确保宽度适配移动端 */
:deep(img) {
max-width: 100% !important;
width: auto !important;
height: auto !important;
display: block !important;
margin: 24rpx auto !important;
border-radius: 12rpx;
}
/* 标题样式优化 */
:deep(h1),
:deep(h2),
:deep(h3),
:deep(h4),
:deep(h5),
:deep(h6) {
margin: 24rpx 0 16rpx;
font-weight: bold;
color: #1F2937;
}
:deep(h1) {
font-size: 40rpx;
}
:deep(h2) {
font-size: 36rpx;
}
:deep(h3) {
font-size: 32rpx;
}
/* 段落样式 */
:deep(p) {
margin: 16rpx 0;
}
/* 列表样式 */
:deep(ul),
:deep(ol) {
padding-left: 32rpx;
margin: 16rpx 0;
}
:deep(li) {
margin: 8rpx 0;
}
/* 引用样式 */
:deep(blockquote) {
padding: 16rpx 24rpx;
margin: 16rpx 0;
background-color: #F3F4F6;
border-left: 4rpx solid #D1D5DB;
color: #6B7280;
}
/* 链接样式 */
:deep(a) {
color: #2563EB;
text-decoration: underline;
}
}
.safe-area-bottom {
height: 120rpx;
}
.footer-bar {
position: fixed;
bottom: 0;
left: 0;
right: 0;
background-color: #fff;
border-top: 1rpx solid #E5E7EB;
padding-bottom: env(safe-area-inset-bottom);
}
.footer-content {
display: flex;
justify-content: center;
align-items: center;
padding: 20rpx 32rpx;
}
.collect-button {
display: flex;
align-items: center;
justify-content: center;
padding: 16rpx 48rpx;
border-radius: 999rpx;
background-color: #F3F4F6;
transition: all 0.2s ease;
&.collected {
background-color: #FEF3C7;
.collect-icon {
color: #F59E0B;
}
.collect-text {
color: #F59E0B;
}
}
}
.collect-icon {
font-size: 32rpx;
color: #9CA3AF;
margin-right: 8rpx;
}
.collect-text {
font-size: 28rpx;
color: #6B7280;
}
.error-state {
display: flex;
justify-content: center;
align-items: center;
min-height: 400rpx;
}
</style>
/*
* @Date: 2026-02-27 13:03:03
* @LastEditors: hookehuyr hookehuyr@gmail.com
* @LastEditTime: 2026-02-27 14:42:14
* @FilePath: /manulife-weapp/src/pages/article-favorites/index.config.js
* @Description: 我的收藏文章页面配置
*/
export default definePageConfig({
navigationBarTitleText: '我的收藏文章',
backgroundColor: '#F9FAFB',
navigationStyle: 'custom'
})
<!--
* @Date: 2026-02-27
* @Description: 文章收藏列表页 - 复用 favorites 页面结构
-->
<template>
<view class="h-screen bg-gray-50 flex flex-col overflow-hidden">
<view class="bg-gray-50 z-10">
<NavHeader title="我的收藏文章" />
</view>
<!-- LoadMoreList 组件 -->
<LoadMoreList
:list="currentList"
:page="currentPage"
:page-size="pageSize"
:has-more="hasMore"
:loading="loading"
:loading-more="loadingMore"
key-field="id"
:show-header="false"
:has-footer="false"
@load-more="handleLoadMore"
>
<!-- 列表项 -->
<template #item="{ item }">
<ArticleCard
:id="item.id"
:title="item.title"
:excerpt="item.excerpt"
:cover-url="item.coverUrl"
:date="item.date"
:collected="item.collected"
@viewed="onView(item)"
@collect-changed="handleCollectChanged(item, $event)"
/>
</template>
</LoadMoreList>
</view>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import Taro, { useLoad } from '@tarojs/taro'
import LoadMoreList from '@/components/list/LoadMoreList'
import ArticleCard from '@/components/cards/ArticleCard.vue'
import NavHeader from '@/components/navigation/NavHeader.vue'
import { favoriteAPI } from '@/api/article'
import { mockArticleFavoriteAPI } from '@/utils/mockData'
import eventBus, { Events } from '@/utils/eventBus'
import { USE_MOCK_DATA } from '@/config/app'
// ⚠️ MOCK 数据开关 - 统一从 @/config/app 导入
// const USE_MOCK_DATA = process.env.NODE_ENV === 'development'
/**
* 当前列表数据
*/
const currentList = ref([])
/**
* 当前页码(从0开始)
*/
const currentPage = ref(0)
/**
* 每页数量
*/
const pageSize = 20
/**
* 是否还有更多数据
*/
const hasMore = ref(true)
/**
* 首次加载状态
*/
const loading = ref(false)
/**
* 加载更多状态
*/
const loadingMore = ref(false)
/**
* 获取文章收藏列表
*
* @param {Object} params - 请求参数
* @param {number} params.page - 页码(从0开始)
* @param {number} params.limit - 每页数量
* @param {boolean} isLoadMore - 是否为加载更多
*/
const fetchFavoritesList = async (params = {}, isLoadMore = false) => {
try {
if (isLoadMore) {
loadingMore.value = true
} else {
loading.value = true
}
console.log('[Article Favorites] 请求参数:', params)
console.log('[Article Favorites] 使用 Mock 数据:', USE_MOCK_DATA)
const res = USE_MOCK_DATA
? await mockArticleFavoriteAPI(params)
: await favoriteAPI({
page: String(params.page),
limit: String(params.limit)
})
if (res.code === 1 && res.data && res.data.list) {
console.log('[Article Favorites] 数据:', res.data.list)
const processedList = res.data.list.map(item => ({
id: item.id,
title: item.post_title || '未命名文章',
excerpt: item.post_excerpt || '',
coverUrl: '',
date: item.post_date || '',
collected: true // 收藏列表中的文章都是已收藏的
}))
if (isLoadMore) {
currentList.value = [...currentList.value, ...processedList]
} else {
currentList.value = processedList
}
hasMore.value = res.data.list.length >= params.limit
} else {
if (!isLoadMore) {
currentList.value = []
}
Taro.showToast({
title: res.msg || '获取收藏列表失败',
icon: 'none'
})
}
} catch (err) {
console.error('[Article Favorites] 获取收藏列表失败:', err)
if (!isLoadMore) {
currentList.value = []
}
Taro.showToast({
title: '网络错误,请稍后重试',
icon: 'none'
})
} finally {
if (isLoadMore) {
loadingMore.value = false
} else {
loading.value = false
}
}
}
/**
* 处理收藏状态改变
*/
const handleCollectChanged = (item, newStatus) => {
console.log('[Article Favorites] 收藏状态改变:', item.title, newStatus.collected)
if (!newStatus.collected) {
// 取消收藏,从列表中移除
const index = currentList.value.findIndex(i => i.id === item.id)
if (index !== -1) {
currentList.value.splice(index, 1)
}
}
}
/**
* 查看文章
*/
const onView = (item) => {
console.log('[Article Favorites] 查看文章:', item.title)
// 跳转到文章详情页
Taro.navigateTo({
url: `/pages/article-detail/index?id=${item.id}`
})
}
/**
* 处理加载更多事件
*/
const handleLoadMore = async (page) => {
console.log('[Article Favorites] 加载更多,页码:', page)
currentPage.value = page
await fetchFavoritesList({ page: page, limit: pageSize }, true)
}
/**
* 刷新收藏列表
*/
const refreshList = async () => {
console.log('[Article Favorites] 刷新列表')
currentPage.value = 0
hasMore.value = true
await fetchFavoritesList({ page: 0, limit: pageSize })
}
/**
* 页面加载时获取列表
*/
useLoad(() => {
console.log('[Article Favorites] 页面加载,获取列表')
currentPage.value = 0
hasMore.value = true
fetchFavoritesList({ page: 0, limit: pageSize })
})
/**
* 监听收藏更新事件
*/
onMounted(() => {
console.log('[Article Favorites] 注册事件监听')
const unsubscribe = eventBus.on(Events.FAVORITES_UPDATE, async () => {
console.log('[Article Favorites] 收到收藏更新事件')
await refreshList()
})
onUnmounted(() => {
unsubscribe()
console.log('[Article Favorites] 取消事件监听')
})
})
</script>
<style lang="less">
/* LoadMoreList 组件已内置样式 */
</style>
......@@ -9,20 +9,51 @@
</div>
<!-- Content List -->
<div v-else-if="sections.length > 0" class="px-[40rpx] mt-[40rpx] relative z-10">
<SectionCard
v-for="(section, index) in sections"
:key="index"
:title="section.title"
:items="section.items"
@item-click="handleItemClick"
/>
<div v-else-if="filteredChildren.length > 0" class="px-[40rpx] mt-[40rpx] relative z-10">
<template v-for="item in filteredChildren" :key="item.id">
<!-- 有子分类:显示 SectionCard -->
<SectionCard
v-if="item.max_depth > 1"
:title="item.category_name"
:items="convertToItems(item.children)"
@item-click="handleItemClick"
/>
<!-- 无子分类且有文章:直接显示 ArticleCard 列表 -->
<template v-else-if="item.max_depth === 1 && item.list?.length">
<view class="bg-white rounded-[32rpx] mb-[32rpx] overflow-hidden shadow-sm">
<!-- 标题区域 - 与 SectionCard 一致 -->
<view class="px-[40rpx] py-[32rpx]" style="background: linear-gradient(90deg, #EFF6FF 0%, #DBEAFE 100%)">
<text class="text-[#1f2937] text-[32rpx] font-normal">{{ item.category_name }}</text>
</view>
<!-- 文章列表 -->
<view class="px-[32rpx] pt-[24rpx] pb-[32rpx]">
<view v-for="(article, index) in item.list" :key="article.id">
<ArticleCard
:id="article.id"
:title="article.post_title"
:excerpt="article.post_excerpt"
:date="article.formatted_post_date || article.post_date"
:collected="article.is_favorite === 1"
:show-cover="false"
@collect-changed="handleCollectChanged"
/>
<!-- 卡片间距(最后一项不显示) -->
<view v-if="index < item.list.length - 1" class="h-[16rpx]"></view>
</view>
</view>
</view>
</template>
</template>
</div>
<!-- Empty State -->
<div v-else class="px-[40rpx] mt-[80rpx] flex items-center justify-center">
<!-- <text class="text-[#9CA3AF] text-[28rpx]">暂无分类</text> -->
<nut-empty description="暂无分类" image="empty" />
<view class="flex flex-col items-center">
<view class="text-[#9CA3AF] text-[120rpx] mb-[24rpx]">📂</view>
<text class="text-gray-600 text-[28rpx]">暂无分类</text>
</view>
</div>
</div>
</template>
......@@ -32,9 +63,12 @@ import { ref, computed } from 'vue'
import { useLoad } from '@tarojs/taro'
import NavHeader from '@/components/navigation/NavHeader.vue'
import SectionCard from '@/components/list/SectionCard.vue'
import { fileListAPI } from '@/api/file'
import ArticleCard from '@/components/cards/ArticleCard.vue'
import { listAPI } from '@/api/article'
import { mockArticleListAPI } from '@/utils/mockData'
import { useGo } from '@/hooks/useGo'
import Taro from '@tarojs/taro'
import { USE_MOCK_DATA } from '@/config/app'
const go = useGo()
......@@ -50,45 +84,23 @@ const data = ref({})
const pageTitle = ref('分类列表')
/**
* 最大层级
* 过滤后的子分类列表
* @description 过滤掉 max_depth === 1 且 list 为空的项
*/
const maxLevel = computed(() => data.value?.max_level || 0)
/**
* 将 API 返回的 children 数据转换为 SectionCard 需要的格式
* @description 将嵌套的 children 数组转换为 sections 格式
*
* 数据结构:
* - 第一层(大标题):level=1,如"入职前"、"入职中"、"入职后"
* - 第二层(小标题):level=2,如"考试报名"、"资格考试报名入口"
*
* @returns {Array<{title: string, items: Array}>}
*/
const sections = computed(() => {
const filteredChildren = computed(() => {
const children = data.value?.children || []
if (children.length === 0) {
return []
}
// 为每个第一层分类创建一个 section
return children.map(level1Category => ({
title: level1Category.category_name, // 大标题:"入职前"
items: (level1Category.children || []).map(level2Category => ({
id: level2Category.id,
title: level2Category.category_name, // 小标题:"考试报名"
subtitle: level2Category.list?.length ? `${level2Category.list.length} 个文件` : '',
icon: level2Category.icon || '',
level: level2Category.level,
maxDepth: level2Category.max_depth,
// 保留原始数据供点击事件使用
_raw: level2Category
}))
}))
return children.filter(item => {
// 保留有子分类的项
if (item.max_depth > 1) return true
// 保留有文章列表的项
if (item.max_depth === 1 && item.list?.length > 0) return true
// 过滤掉空项
return false
})
})
/**
* 获取文分类列表
* 获取文分类列表
* @param {Object} options - 页面参数
* @param {string} options.cid - 分类ID(首次进入)
* @param {string} options.id - 子分类ID(后续层级)
......@@ -107,15 +119,16 @@ const fetchCategoryList = async (options) => {
}
console.log('[Category List] 请求参数:', params)
console.log('[Category List] 使用 Mock 数据:', USE_MOCK_DATA)
// 调用接口(直接调用,不使用 fn() 包装)
const res = await fileListAPI(params)
// 调用文章列表接口(支持分类结构)
const res = USE_MOCK_DATA
? await mockArticleListAPI(params)
: await listAPI(params)
if (res.code === 1 && res.data) {
data.value = res.data
// console.log('[Category List] 分类数据:', res.data)
// console.log('[Category List] 最大层级:', maxLevel.value)
// console.log('[Category List] 转换后的 sections:', JSON.stringify(sections.value, null, 2))
console.log('[Category List] 分类数据:', res.data)
} else {
Taro.showToast({
title: res.msg || '获取分类列表失败',
......@@ -152,8 +165,8 @@ const handleItemClickWithNav = (item, go) => {
console.log('[Category List] 分类层级:', item.level)
console.log('[Category List] 最大深度:', item.maxDepth)
// 当前点击的是第二层(level=2),直接跳转到文列表
console.log('[Category List] 跳转到文列表')
// 当前点击的是第二层(level=2),直接跳转到文列表
console.log('[Category List] 跳转到文列表')
go('/pages/material-list/index', {
id: item.id,
title: item.title
......@@ -164,6 +177,33 @@ const handleItemClickWithNav = (item, go) => {
const handleItemClick = (item) => handleItemClickWithNav(item, go)
/**
* 将子分类数组转换为 SectionCard items 格式
* @param {Array} children - 子分类数组
* @returns {Array} SectionCard items 格式
*/
const convertToItems = (children) => {
if (!children || children.length === 0) return []
return children.map(category => ({
id: category.id,
title: category.category_name,
subtitle: category.list?.length ? `${category.list.length} 篇文章` : '',
icon: category.icon || '',
level: category.level,
maxDepth: category.max_depth,
_raw: category
}))
}
/**
* 处理收藏状态变化
* @param {Object} payload - 收藏事件数据
*/
const handleCollectChanged = (payload) => {
console.log('[Category List] 收藏状态变化:', payload)
// TODO: 更新本地状态或刷新列表
}
/**
* 页面加载时接收参数并初始化
*/
useLoad((options) => {
......