bookshelf.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // pages/bookshelf/bookshelf.js
  2. const bookshelfApi = require('../../api/bookshelf');
  3. const contentApi = require('../../api/content');
  4. const userUtil = require('../../utils/user');
  5. Page({
  6. data: {
  7. bookshelf: [],
  8. contentList: [],
  9. loading: false
  10. },
  11. onLoad() {
  12. this.loadBookshelf();
  13. },
  14. onShow() {
  15. this.loadBookshelf();
  16. },
  17. // 加载书架
  18. async loadBookshelf() {
  19. if (!userUtil.isLogin()) {
  20. this.setData({ bookshelf: [], contentList: [] });
  21. return;
  22. }
  23. this.setData({ loading: true });
  24. try {
  25. const userInfo = userUtil.getUserInfo();
  26. const bookshelf = await bookshelfApi.getBookshelfList(userInfo.userId);
  27. // 获取书籍详情
  28. const contentList = [];
  29. for (const item of bookshelf) {
  30. try {
  31. const content = await contentApi.getContentDetail(item.contentId);
  32. contentList.push({
  33. ...content,
  34. addTime: item.addTime,
  35. lastAccessTime: item.lastAccessTime
  36. });
  37. } catch (error) {
  38. console.error('加载书籍详情失败:', error);
  39. }
  40. }
  41. this.setData({
  42. bookshelf,
  43. contentList
  44. });
  45. // 同时保存到本地
  46. wx.setStorageSync('bookshelf', contentList);
  47. } catch (error) {
  48. console.error('加载书架失败:', error);
  49. // 失败时从本地加载
  50. const localBookshelf = wx.getStorageSync('bookshelf') || [];
  51. this.setData({ contentList: localBookshelf });
  52. } finally {
  53. this.setData({ loading: false });
  54. }
  55. },
  56. // 跳转到详情
  57. goToDetail(e) {
  58. const contentId = e.currentTarget.dataset.id;
  59. wx.navigateTo({
  60. url: `/pages/detail/detail?id=${contentId}`
  61. });
  62. }
  63. });