123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415 |
- Page({
- data: {
- showComment: false,
- currentCommentId: '',
- commentContent: '',
- showPreview: false, // 控制预览模态框显示
- previewImages: [], // 预览图片数组
- previewIndex: 0 , // 当前预览索引
- tabs: [
- { id: 'recommend', name: '推荐' },
- { id: 'notes', name: '研学笔记' },
- { id: 'reports', name: '实践报告' },
- { id: 'experience', name: '考察心得' }
- ],
- activeTab: 'recommend',
- scrollLeft: 0,
- tabHeight: 44,
-
- // 卡片数据
- allData: {
- recommend: [],
- notes: [],
- reports: [],
- experience: []
- },
- currentData: [],
- pageSize: 10,
- currentPage: {
- recommend: 1,
- notes: 1,
- reports: 1,
- experience: 1
- },
- hasMore: {
- recommend: true,
- notes: true,
- reports: true,
- experience: true
- },
- loading: false,
- needRefresh:false
- },
- onLoad() {
- // 绑定方法确保上下文正确
- this.addNewCard = this.addNewCard.bind(this);
- this.onNewPublish = this.onNewPublish.bind(this);
-
- // 初始化数据
- this.initData();
- setTimeout(() => {
- this.checkPendingPublish();
- }, 300);
- // 加载数据
- this.loadAllTabData();
- this.checkPendingPublish();
- },
- initData() {
- this.setData({
- allData: {
- recommend: [],
- notes: [],
- reports: [],
- experience: []
- },
- currentData: []
- });
- },
- loadAllTabData() {
- ['recommend', 'notes', 'reports', 'experience'].forEach(tab => {
- this.loadTabData(tab);
- });
- },
- loadTabData(tabId, page = 1) {
- if (this.data.loading) return;
-
- this.setData({ loading: true });
-
- setTimeout(() => {
- const mockData = this.generateMockData(tabId, page);
- const newData = page === 1 ? mockData : [...this.data.allData[tabId], ...mockData];
-
- this.setData({
- [`allData.${tabId}`]: newData,
- currentData: this.data.activeTab === tabId ? newData : this.data.currentData,
- loading: false
- });
-
- if (page === 1) {
- wx.pageScrollTo({ scrollTop: 0, duration: 300 });
- }
- }, 800);
- },
- // 切换Tab
- switchTab(e) {
- const tabId = e.currentTarget.dataset.id;
- if (this.data.activeTab === tabId) return;
-
- this.setData({
- activeTab: tabId,
- currentData: this.data.allData[tabId] || []
- });
-
- // 如果当前Tab没有数据,则加载
- if (this.data.allData[tabId].length === 0) {
- this.loadTabData(tabId);
- }
- },
- // 加载Tab数据
- loadTabData(tabId, page = 1) {
- if (this.data.loading) return;
-
- this.setData({ loading: true });
-
- // 模拟API请求
- setTimeout(() => {
- // 模拟数据
- const mockData = this.generateMockData(tabId, page);
-
- // 更新数据
- const newData = page === 1
- ? mockData
- : [...this.data.allData[tabId], ...mockData];
-
- this.setData({
- [`allData.${tabId}`]: newData,
- currentData: newData,
- [`currentPage.${tabId}`]: page,
- [`hasMore.${tabId}`]: mockData.length >= this.data.pageSize,
- loading: false
- });
-
- // 如果是第一页,滚动到顶部
- if (page === 1) {
- wx.pageScrollTo({
- scrollTop: 0,
- duration: 300
- });
- }
- }, 800);
- },
- // 生成模拟数据
- generateMockData(tabId, page) {
- const data = [];
- const count = page === 3 ? 5 : this.data.pageSize; // 模拟最后一页数据不足
-
- for (let i = 0; i < count; i++) {
- data.push({
- id: `${tabId}_${page}_${i}`,
- images: this.generateMockImages(), // 必须包含有效图片数组
- user: {
- avatar: 'https://randomuser.me/api/portraits/thumb/men/' + (Math.floor(Math.random() * 100)) + '.jpg',
- name: ['张', '王', '李', '赵', '钱'][Math.floor(Math.random() * 5)] + '同学'
- },
- createTime: `${Math.floor(Math.random() * 12) + 1}小时前`,
- title: `${this.getTabTitle(tabId)} ${page * this.data.pageSize + i + 1}`,
- content: `这是${this.getTabTitle(tabId)}的内容示例,这里可以展示用户发布的具体内容。${tabId}内容区域可以展示多种形式的内容卡片。`,
- images: this.generateMockImages(),
- likeCount: Math.floor(Math.random() * 100),
- commentCount: Math.floor(Math.random() * 50),
- collectCount: Math.floor(Math.random() * 30)
- });
- }
- return data;
- },
- // 生成模拟图片
- generateMockImages() {
- const count = Math.min(4, Math.floor(Math.random() * 4) + 1); // 1-4张
- return Array.from({length: count}, (_, i) =>
- `https://picsum.photos/300/200?random=${Date.now()}_${i}`
- );
- },
- // 获取Tab标题
- getTabTitle(tabId) {
- const tab = this.data.tabs.find(item => item.id === tabId);
- return tab ? tab.name : '';
- },
- // 上拉加载更多
- onReachBottom() {
- const { activeTab, currentPage, hasMore } = this.data;
- if (!hasMore[activeTab] || this.data.loading) return;
-
- this.loadTabData(activeTab, currentPage[activeTab] + 1);
- },
- // 下拉刷新
- onPullDownRefresh() {
- this.loadTabData(this.data.activeTab, 1);
- wx.stopPullDownRefresh();
- },
- navigateToPublish() {
- wx.navigateTo({
- url: '/pages/publish/publish'
- });
- },
- onNewPublish(newCard) {
- console.log('收到新发布卡片:', newCard);
- if (this.addNewCard && typeof this.addNewCard === 'function') {
- this.addNewCard(newCard, newCard.type);
- } else {
- console.error('addNewCard方法不可用');
- // 降级处理:使用全局数据
- getApp().globalData.lastPublishedCard = newCard;
- }
- },
- // 检查待处理的发布
- checkPendingPublish() {
- const app = getApp();
-
- // 1. 检查全局数据(不删除原有数据)
- if (app.globalData?.lastPublishedCard) {
- this.addNewCard(app.globalData.lastPublishedCard,
- app.globalData.lastPublishedCard.type);
- // 不清空,避免影响其他页面
- }
-
- // 2. 检查本地存储
- try {
- const storedCard = wx.getStorageSync('lastPublishedCard');
- if (storedCard) {
- this.addNewCard(storedCard, storedCard.type);
- wx.removeStorageSync('lastPublishedCard');
- }
- } catch (e) {
- console.error('读取本地存储失败:', e);
- }
- },
- addNewCard(newCard, cardType) {
- const targetType = this.getTargetType(cardType);
- const { allData, activeTab } = this.data;
- // 深度拷贝原有数据
- const updatedAllData = JSON.parse(JSON.stringify(allData));
-
- // 合并新数据
- updatedAllData[targetType] = [newCard, ...(updatedAllData[targetType] || [])];
- updatedAllData.recommend = [newCard, ...(updatedAllData.recommend || [])];
- this.setData({
- allData: updatedAllData,
- currentData: activeTab === 'recommend' || activeTab === targetType
- ? [newCard, ...this.data.currentData]
- : this.data.currentData
- }, () => {
- wx.pageScrollTo({ scrollTop: 0 });
- console.log('数据合并完成', this.data.allData);
- });
- },
- getTargetType(cardType) {
- return cardType === '实践报告' ? 'reports' :
- cardType === '考察心得' ? 'experience' : 'notes';
- },
-
- onShow() {
- const app = getApp();
-
- // 处理全局待发布卡片
- if (app.globalData.pendingCard) {
- this.addNewCard(app.globalData.pendingCard.card, app.globalData.pendingCard.type);
- app.globalData.pendingCard = null;
- }
-
- // 处理刷新标记
- if (this.data.needRefresh) {
- this.loadTabData(this.data.activeTab, 1);
- this.setData({ needRefresh: false });
- }
- },
- checkPendingPublish() {
- const app = getApp();
-
- // 1. 检查全局数据
- if (app.globalData?.lastPublishedCard) {
- console.log('处理全局数据中的待发布卡片');
- this.addNewCard(app.globalData.lastPublishedCard, app.globalData.lastPublishedCard.type);
- app.globalData.lastPublishedCard = null;
- return; // 处理完就返回,避免重复处理
- }
-
- // 2. 检查本地存储
- try {
- const storedCard = wx.getStorageSync('lastPublishedCard');
- if (storedCard) {
- console.log('处理本地存储中的待发布卡片');
- this.addNewCard(storedCard, storedCard.type);
- wx.removeStorageSync('lastPublishedCard');
- }
- } catch (e) {
- console.error('读取本地存储失败:', e);
- }
- },
- // 添加 loadInitialData 方法(如果确实需要)
- loadInitialData() {
- // 这里可以放一些初始化数据的逻辑
- console.log('执行初始化数据加载');
- },
- // 点赞处理
- handleLike(e) {
- const cardId = e.currentTarget.dataset.id;
- this.updateCardData(cardId, (item) => ({
- isLiked: !item.isLiked,
- likeCount: item.isLiked ? item.likeCount - 1 : item.likeCount + 1
- }));
- },
- // 收藏处理
- handleCollect(e) {
- const cardId = e.currentTarget.dataset.id;
- this.updateCardData(cardId, (item) => ({
- isCollected: !item.isCollected,
- collectCount: item.isCollected ? item.collectCount - 1 : item.collectCount + 1
- }));
- },
- // 通用数据更新方法
- updateCardData(cardId, updateFn) {
- const { allData, currentData, activeTab } = this.data;
-
- // 深拷贝数据
- const newAllData = JSON.parse(JSON.stringify(allData));
- let newCurrentData = [...currentData];
- // 更新所有分类中的数据
- Object.keys(newAllData).forEach(tab => {
- newAllData[tab] = newAllData[tab].map(item => {
- if (item.id === cardId) {
- return { ...item, ...updateFn(item) };
- }
- return item;
- });
- });
- // 更新当前显示数据
- newCurrentData = newCurrentData.map(item => {
- if (item.id === cardId) {
- return { ...item, ...updateFn(item) };
- }
- return item;
- });
- this.setData({
- allData: newAllData,
- currentData: newCurrentData
- });
- },
- // 图片预览功能(增强版)
- previewImage(e) {
- const { urls, index } = e.currentTarget.dataset;
- wx.previewImage({
- current: urls[index], // 当前点击图片url
- urls: urls, // 所有图片url列表
- success: () => {
- this.setData({
- showPreview: true,
- previewImages: urls,
- previewIndex: index
- });
- },
- fail: (err) => {
- console.error('预览失败:', err);
- wx.showToast({ title: '预览失败', icon: 'none' });
- }
- });
- },
- // 关闭预览
- closePreview() {
- this.setData({ showPreview: false });
- },
- // 图片预览功能
- previewImage(e) {
- // 多重保障获取图片数组
- const urls = e.currentTarget.dataset.urls ||
- this.data.currentData.find(
- item => item.images &&
- item.images.includes(e.currentTarget.dataset.current)
- )?.images || [];
- const current = e.currentTarget.dataset.current;
- if (!urls.length) {
- console.error('无效图片参数:', {
- dataset: e.currentTarget.dataset,
- currentData: this.data.currentData
- });
- wx.showToast({ title: '暂无可预览图片', icon: 'none' });
- return;
- }
- wx.previewImage({
- current: current,
- urls: urls,
- fail: (err) => {
- console.error('预览失败:', err);
- wx.showToast({ title: '预览失败', icon: 'none' });
- }
- });
- },
- // 关闭预览
- closePreview() {
- this.setData({ showPreview: false });
- },
- });
|