| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753 |
- <template>
- <view class="detail-container">
- <!-- 调试信息 -->
- <view v-if="debugInfo" class="debug-info">
- <text>调试信息: novelId={{novelId}}, loading={{loading}}, error={{error}}</text>
- </view>
-
- <!-- 加载状态 -->
- <view v-if="loading" class="loading-container">
- <uni-icons type="spinner-cycle" size="36" color="var(--primary-color)" class="loading-icon" />
- <text>加载中...</text>
- </view>
-
- <!-- 错误状态 -->
- <view v-else-if="error" class="error-container">
- <uni-icons type="info" size="48" color="var(--error-color)" />
- <text class="error-text">{{ error }}</text>
- <button class="btn-retry" @click="initDetail">重新加载</button>
- </view>
-
- <!-- 内容区域 -->
- <view v-else class="content-container">
- <!-- 小说封面和基本信息 -->
- <view class="novel-header">
- <!-- 修改封面图片绑定 -->
- <image
- :src="getSafeCoverUrl(novel.coverImg)"
- class="novel-cover"
- mode="aspectFill"
- @error="handleCoverError"
- />
- <view class="novel-info">
- <text class="update-time">
- 更新时间: {{ formatTime(novel.updateTime) }}
- </text>
- <text class="novel-title">{{ novel.title || '未知小说' }}</text>
- <text class="novel-author">{{ novel.author || '未知作者' }}</text>
- <text class="novel-meta">{{ novel.categoryName || '未知分类' }} · {{ novel.statusText || '连载中' }}</text>
- <text class="novel-meta">{{ (novel.wordCount || 0) }}字 · {{ (novel.readCount || 0) }}阅读</text>
- </view>
- </view>
-
- <!-- 小说描述 -->
- <view class="description-section">
- <text class="section-title">作品简介</text>
- <text class="novel-description">{{ novel.description || '暂无简介' }}</text>
- </view>
-
- <!-- 操作按钮 -->
- <view class="action-buttons">
- <button
- class="btn-add-bookshelf"
- :class="{ 'in-bookshelf': isInBookshelf }"
- @click="addToBookshelf"
- >
- {{ isInBookshelf ? '已在书架' : '加入书架' }}
- </button>
- <button class="btn-start-reading" @click="startReading">
- 开始阅读
- </button>
- </view>
-
- <!-- 章节列表 -->
- <view class="chapter-preview">
- <view class="section-header">
- <text class="section-title">章节列表</text>
- <text class="section-more" @click="showAllChapters = !showAllChapters">
- {{ showAllChapters ? '收起' : '展开' }}
- </text>
- </view>
- <view v-if="displayedChapters.length > 0" class="chapter-list">
- <view
- v-for="chapter in displayedChapters"
- :key="chapter.id"
- class="chapter-item"
- @click="readChapter(chapter)"
- >
- <text class="chapter-title">{{ chapter.title }}</text>
- <text class="chapter-time">
- {{ formatTime(chapter.updateTime, 'MM-DD HH:mm') }}
- </text>
- </view>
- </view>
- <view v-else class="empty-chapters">
- <text>暂无章节</text>
- </view>
- </view>
- </view>
- </view>
- </template>
-
- <script>
- // 导入 request 模块
- import request from '@/utils/request'
- import { getToken, setToken, removeToken } from '@/utils/auth'
-
- export default {
- data() {
- return {
- novelId: null,
- novel: {},
- chapters: [],
- loading: true,
- error: null,
- isInBookshelf: false,
- showAllChapters: false,
- debugInfo: true
- }
- },
-
- computed: {
- // 显示前5章或全部章节
- displayedChapters() {
- if (this.showAllChapters) {
- return this.chapters;
- }
- return this.chapters.slice(0, 5);
- }
- },
-
- onLoad(options) {
- console.log('🚨 DETAIL onLoad 开始执行');
- this.novelId = options.id || this.$route.params.id;
- console.log('🔍 最终 novelId:', this.novelId);
-
- if (!this.novelId) {
- this.error = '无法获取小说信息';
- this.loading = false;
- return;
- }
-
- this.initDetail();
- },
-
- mounted() {
- // 检查 uni 对象是否可用
- if (typeof uni === 'undefined') {
- console.warn('⚠️ uni 对象未定义,使用 Vue Router 进行导航');
- } else {
- console.log('✅ uni 对象可用:', typeof uni.navigateTo);
- }
- console.log('🚨 DETAIL mounted 执行');
- // 备选方案:如果onLoad没有获取到参数,在这里再次尝试
- if (!this.novelId) {
- console.log('🔄 mounted中重新获取参数');
- this.novelId = this.$route.params.id;
- if (this.novelId) {
- this.initDetail();
- }
- }
- },
-
- methods: {
- // 格式化时间
- formatTime(time, format = 'YYYY-MM-DD HH:mm') {
- if (!time) return ''
-
- const date = new Date(time)
- const year = date.getFullYear()
- const month = String(date.getMonth() + 1).padStart(2, '0')
- const day = String(date.getDate()).padStart(2, '0')
- const hour = String(date.getHours()).padStart(2, '0')
- const minute = String(date.getMinutes()).padStart(2, '0')
- const second = String(date.getSeconds()).padStart(2, '0')
-
- return format
- .replace('YYYY', year)
- .replace('MM', month)
- .replace('DD', day)
- .replace('HH', hour)
- .replace('mm', minute)
- .replace('ss', second)
- },
-
- // 或者使用更简单的时间格式化
- formatTimeSimple(time) {
- if (!time) return ''
- const date = new Date(time)
- return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
- },
-
- async initDetail() {
- try {
- console.log('🎬 initDetail 开始执行,novelId:', this.novelId)
- this.loading = true
- this.error = null
-
- // 并行请求小说详情和章节列表
- const [detailRes, chaptersRes] = await Promise.allSettled([
- this.loadNovelDetail(),
- this.loadChapters()
- ])
-
- // 处理结果
- if (detailRes.status === 'fulfilled') {
- console.log('✅ 小说详情加载完成')
- } else {
- console.error('❌ 小说详情加载失败:', detailRes.reason)
- }
-
- if (chaptersRes.status === 'fulfilled') {
- console.log('✅ 章节列表加载完成')
- } else {
- console.error('❌ 章节列表加载失败:', chaptersRes.reason)
- }
-
- // 检查书架状态
- this.checkBookshelfStatus()
-
- } catch (error) {
- console.error('🎬 initDetail 执行失败:', error)
- this.error = '加载失败,请重试'
- } finally {
- this.loading = false
- }
- },
-
- async loadNovelDetail() {
- try {
- console.log('📚 开始加载小说详情...')
- // 明确设置不携带token
- const res = await request.get(`/novel/detail/${this.novelId}`, {}, {
- header: {
- isToken: false
- }
- })
-
- console.log('✅ 小说详情API响应:', res)
-
- if (res && res.code === 200 && res.data) {
- this.novel = res.data
- console.log('📖 小说详情数据:', this.novel)
- } else {
- console.warn('⚠️ 小说详情接口返回数据异常,使用模拟数据')
- // 使用模拟数据的逻辑
- this.useMockData()
- }
- } catch (error) {
- console.error('❌ 加载小说详情失败:', error)
- console.warn('⚠️ 网络请求失败,使用模拟数据')
- this.useMockData()
- }
- },
-
- // detail.vue 中修改 loadChapters 方法
- async loadChapters() {
- try {
- console.log('📑 开始加载章节列表...');
-
- // 尝试获取token
- const token = uni.getStorageSync('token');
- console.log('🔑 当前token状态:', token ? '已存在' : '不存在');
-
- let requestConfig = {
- header: {
- isToken: false
- }
- };
-
- // 如果有token,使用token请求
- if (token) {
- requestConfig = {
- header: {
- 'Authorization': 'Bearer ' + token,
- isToken: true
- }
- };
- console.log('🔐 使用token请求章节列表');
- } else {
- console.log('👤 使用公开API请求章节列表');
- }
-
- // 尝试请求真实数据
- const res = await request.get(`/chapter/list/${this.novelId}`, {}, requestConfig);
-
- console.log('✅ 章节列表API响应:', res);
-
- if (res && res.code === 200 && res.rows) {
- // 注意:后端返回的是 res.rows,不是 res.data
- this.chapters = res.rows;
- console.log('📑 章节列表数据:', this.chapters);
- } else if (res && res.rows) {
- // 如果直接返回 rows 数组
- this.chapters = res.rows;
- console.log('📑 章节列表数据(rows):', this.chapters);
- } else {
- console.warn('⚠️ 章节列表接口返回异常,使用模拟数据');
- this.useMockChapters();
- }
- } catch (error) {
- console.error('❌ 加载章节列表失败:', error);
-
- // 如果是401错误,提示用户登录
- if (error.message && error.message.includes('认证失败')) {
- uni.showToast({
- title: '请登录后查看章节',
- icon: 'none'
- });
- }
-
- console.warn('⚠️ 网络请求失败,使用模拟章节数据');
- this.useMockChapters();
- }
- },
-
- // 改进模拟数据生成
- useMockChapters() {
- console.log('🎭 生成模拟章节数据');
- const mockChapters = [];
- const chapterTitles = [
- '初遇异能者', '白冰的身世', '小队集结', '首次任务', '危机四伏',
- '突破极限', '新的伙伴', '黑暗组织', '真相大白', '最终决战'
- ];
-
- // 生成更真实的模拟数据
- for (let i = 0; i < 15; i++) {
- const chapterNum = i + 1;
- const titleIndex = i % chapterTitles.length;
- mockChapters.push({
- id: chapterNum,
- title: `第${chapterNum}章 ${chapterTitles[titleIndex]}`,
- updateTime: new Date(Date.now() - (15 - i) * 24 * 60 * 60 * 1000),
- content: `这是第${chapterNum}章的内容...`,
- wordCount: Math.floor(Math.random() * 3000) + 1500
- });
- }
-
- this.chapters = mockChapters;
- console.log('📚 模拟章节数据生成完成:', this.chapters.length + '章');
- },
-
-
- useMockChapters() {
- // 你的模拟章节数据逻辑
- this.chapters = [
- { id: 1, title: '第一章 初遇', updateTime: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000) },
- { id: 2, title: '第二章 相识', updateTime: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000) },
- { id: 3, title: '第三章 冒险开始', updateTime: new Date() }
- ]
- },
-
- // 其他方法保持不变...
- getSafeCoverUrl(coverImg) {
- if (!coverImg) return '/static/default-cover.jpg';
- if (coverImg && !coverImg.includes('ishuquge.org') && !coverImg.includes('xshuquge.net')) {
- return coverImg;
- }
- return '/static/default-cover.jpg';
- },
-
- handleCoverError(event) {
- console.log('封面图片加载失败,使用默认图片');
- // 注意:在小程序中,可能需要使用不同的方式处理图片错误
- this.novel.coverImg = '/static/default-cover.jpg';
- },
-
- // 检查书架状态
- checkBookshelfStatus() {
- try {
- const bookshelf = uni.getStorageSync('user_bookshelf') || [];
- this.isInBookshelf = bookshelf.some(item => item.novelId == this.novelId);
- console.log('📚 书架状态:', this.isInBookshelf ? '已在书架' : '未在书架');
- } catch (error) {
- console.error('检查书架状态失败:', error);
- }
- },
-
- // 加入书架
- addToBookshelf() {
- console.log('📚 加入书架 clicked');
-
- // 立即更新状态
- this.isInBookshelf = true;
-
- // 保存到本地存储
- try {
- const bookshelf = uni.getStorageSync('user_bookshelf') || [];
- const existingIndex = bookshelf.findIndex(item => item.novelId == this.novelId);
-
- if (existingIndex === -1) {
- bookshelf.push({
- novelId: this.novelId,
- novel: this.novel,
- addTime: new Date().getTime(),
- lastReadChapter: 0
- });
- uni.setStorageSync('user_bookshelf', bookshelf);
- }
-
- uni.showToast({
- title: '加入书架成功',
- icon: 'success',
- duration: 2000
- });
-
- console.log('✅ 加入书架成功');
-
- } catch (error) {
- console.error('保存到书架失败:', error);
- uni.showToast({
- title: '加入书架失败',
- icon: 'none'
- });
- }
- },
-
- // 开始阅读
- startReading() {
- console.log('📖 开始阅读 clicked, novelId:', this.novelId);
-
- if (this.chapters.length === 0) {
- uni.showToast({
- title: '暂无章节',
- icon: 'none'
- });
- return;
- }
-
- const firstChapterId = this.chapters[0].id || 1;
-
- console.log('🎯 跳转到阅读器,参数:', {
- novelId: this.novelId,
- chapterId: firstChapterId
- });
-
- // 安全跳转方法
- this.safeNavigateToReader(this.novelId, firstChapterId);
- },
-
- // 阅读指定章节
- readChapter(chapter) {
- console.log('阅读章节:', chapter);
- const chapterId = chapter.id;
-
- this.safeNavigateToReader(this.novelId, chapterId);
- },
-
- // 安全跳转到阅读器
- // 安全跳转到阅读器
- safeNavigateToReader(novelId, chapterId) {
- console.log('🔒 安全跳转: novelId=' + novelId + ', chapterId=' + chapterId);
-
- // 方法1: 使用 uni.navigateTo (小程序环境)
- try {
- console.log('🔄 尝试使用 uni.navigateTo 跳转...');
-
- // 检查目标页面是否存在
- const pages = getCurrentPages();
- console.log('📄 当前页面栈:', pages.length);
-
- // 构建跳转URL - 确保路径正确
- const targetUrl = `/pages/novel/reader?novelId=${novelId}&chapterId=${chapterId}`;
- console.log('🎯 跳转目标URL:', targetUrl);
-
- uni.navigateTo({
- url: targetUrl,
- success: (res) => {
- console.log('✅ uni.navigateTo 跳转成功', res);
- },
- fail: (err) => {
- console.error('❌ uni.navigateTo 跳转失败:', err);
- this.fallbackNavigate(novelId, chapterId);
- }
- });
-
- } catch (uniError) {
- console.error('❌ uni.navigateTo 异常:', uniError);
- this.fallbackNavigate(novelId, chapterId);
- }
- },
-
- // 备选跳转方案
- fallbackNavigate(novelId, chapterId) {
- console.log('🔄 启动备选跳转方案');
-
- // 方法2: 直接使用 Vue Router (H5环境)
- try {
- console.log('🔄 尝试使用 Vue Router 跳转...');
- if (this.$router) {
- this.$router.push({
- path: '/pages/novel/reader',
- query: {
- novelId: novelId,
- chapterId: chapterId
- }
- });
- console.log('✅ Vue Router 跳转成功');
- return;
- }
- } catch (routerError) {
- console.error('❌ Vue Router 跳转失败:', routerError);
- }
-
- // 方法3: 使用相对路径
- try {
- console.log('🔄 尝试使用相对路径跳转...');
- const currentPath = window.location.pathname;
- const basePath = currentPath.substring(0, currentPath.lastIndexOf('/'));
- const targetUrl = `${basePath}/reader?novelId=${novelId}&chapterId=${chapterId}`;
-
- window.location.href = targetUrl;
- console.log('✅ 相对路径跳转成功');
- return;
- } catch (locationError) {
- console.error('❌ 相对路径跳转失败:', locationError);
- }
-
- // 所有方法都失败
- console.error('💥 所有跳转方法都失败了');
- uni.showToast({
- title: '跳转失败,请检查阅读器页面是否存在',
- icon: 'none',
- duration: 3000
- });
- },
-
-
-
-
-
- // 生成模拟小说数据
- useMockNovelData() {
- this.novel = {
- title: '曦与她的冰姐姐',
- author: '旺旺碎冰冰big',
- categoryName: '都市言情',
- statusText: '已完结',
- wordCount: 118383,
- readCount: 9972,
- description: '这是一个异能者的世界。孤曦和白冰都可谓同年龄天才。十岁的相遇。十五岁同队。这是一个小队成长的故事。白冰又有什么样的身世呢。变异生物和人类最终的大结局会是怎样?内多人物。'
- };
- },
-
- // 生成模拟章节数据
- generateMockChapters() {
- const chapters = [];
- const chapterTitles = [
- '初遇', '相识', '冒险开始', '新的伙伴', '危机降临',
- '突破', '成长', '离别', '重逢', '最终决战'
- ];
-
- for (let i = 0; i < 10; i++) {
- chapters.push({
- id: i + 1,
- title: `第${i + 1}章 ${chapterTitles[i] || '新的篇章'}`,
- updateTime: new Date(Date.now() - (10 - i) * 24 * 60 * 60 * 1000)
- });
- }
- return chapters;
- }
- }
- }
- </script>
-
- <style scoped>
- .detail-container {
- padding: 20rpx;
- min-height: 100vh;
- background-color: #f5f5f5;
- }
-
- /* 调试信息样式 */
- .debug-info {
- background: #ffeb3b;
- color: #333;
- padding: 10rpx;
- font-size: 24rpx;
- text-align: center;
- border-bottom: 1rpx solid #ffc107;
- }
-
- .loading-container, .error-container {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- padding: 200rpx 0;
- text-align: center;
- }
-
- .loading-icon {
- animation: rotate 1s linear infinite;
- margin-bottom: 20rpx;
- }
-
- @keyframes rotate {
- from { transform: rotate(0deg); }
- to { transform: rotate(360deg); }
- }
-
- .error-text {
- font-size: 32rpx;
- color: var(--error-color);
- margin: 20rpx 0;
- }
-
- .btn-retry {
- background-color: var(--primary-color);
- color: white;
- padding: 20rpx 40rpx;
- border-radius: 10rpx;
- margin-top: 20rpx;
- }
-
- .novel-header {
- display: flex;
- background: white;
- padding: 30rpx;
- border-radius: 16rpx;
- margin-bottom: 30rpx;
- }
-
- .novel-cover {
- width: 200rpx;
- height: 280rpx;
- border-radius: 12rpx;
- margin-right: 30rpx;
- background-color: #f0f0f0;
- }
-
- .novel-info {
- flex: 1;
- display: flex;
- flex-direction: column;
- }
-
- .novel-title {
- font-size: 36rpx;
- font-weight: bold;
- margin-bottom: 15rpx;
- line-height: 1.4;
- }
-
- .novel-author {
- font-size: 30rpx;
- color: #666;
- margin-bottom: 10rpx;
- }
-
- .novel-meta {
- font-size: 26rpx;
- color: #888;
- margin-bottom: 8rpx;
- }
-
- .description-section {
- background: white;
- padding: 30rpx;
- border-radius: 16rpx;
- margin-bottom: 30rpx;
- }
-
- .section-title {
- font-size: 32rpx;
- font-weight: bold;
- margin-bottom: 20rpx;
- display: block;
- }
-
- .novel-description {
- font-size: 28rpx;
- line-height: 1.6;
- color: #666;
- }
-
- .action-buttons {
- display: flex;
- gap: 20rpx;
- margin-bottom: 30rpx;
- }
-
- .btn-add-bookshelf, .btn-start-reading {
- flex: 1;
- padding: 25rpx;
- border-radius: 12rpx;
- font-size: 30rpx;
- text-align: center;
- transition: all 0.3s;
- }
-
- .btn-add-bookshelf {
- background-color: #f8f9fa;
- color: var(--primary-color);
- border: 2rpx solid var(--primary-color);
- }
-
- .btn-add-bookshelf.in-bookshelf {
- background-color: #e8f5e8;
- color: #67c23a;
- border-color: #67c23a;
- }
-
- .btn-start-reading {
- background-color: var(--primary-color);
- color: white;
- }
-
- .btn-start-reading:active {
- opacity: 0.8;
- }
-
- .chapter-preview {
- background: white;
- padding: 30rpx;
- border-radius: 16rpx;
- }
-
- .section-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- margin-bottom: 20rpx;
- }
-
- .section-more {
- font-size: 26rpx;
- color: var(--primary-color);
- }
-
- .chapter-list {
- margin-bottom: 20rpx;
- }
-
- .chapter-item {
- display: flex;
- justify-content: space-between;
- align-items: center;
- padding: 20rpx 0;
- border-bottom: 1rpx solid #f0f0f0;
- cursor: pointer;
- }
-
- .chapter-item:last-child {
- border-bottom: none;
- }
-
- .chapter-title {
- font-size: 28rpx;
- color: #333;
- flex: 1;
- }
-
- .chapter-time {
- font-size: 24rpx;
- color: #999;
- }
-
- .empty-chapters {
- text-align: center;
- padding: 40rpx;
- color: #999;
- }
- </style>
|