// pages/compare_price/index.js const API = require('../../utils/api.js'); Page({ data: { // 页面数据 showTips: true, goods: [], loading: false, selectedOption: '' }, onLoad: function (options) { // 页面加载 console.log('对比价格页面加载'); }, onShow: function () { // 页面显示 }, onHide: function () { // 页面隐藏 }, onUnload: function () { // 页面卸载 }, onPullDownRefresh: function () { // 下拉刷新 }, onReachBottom: function () { // 上拉触底 }, // 图片加载完成事件 onImageLoad: function (e) { // 图片加载完成后的处理逻辑 console.log('图片加载完成:', e); }, // 关闭提示弹窗 closeTips: function () { this.setData({ showTips: false }); }, // 选择选项 selectOption: function (e) { const option = e.currentTarget.dataset.option; console.log('选择了:', option); // 显示加载状态 this.setData({ loading: true, selectedOption: option }); // 调用 API 获取符合条件的商品 API.getProducts(1, 20, 'all', '') .then(res => { console.log('获取商品列表成功:', res); // 过滤出 category 匹配且 price 不为 null 的商品 const filteredGoods = res.products.filter(item => item.category === option && item.status === 'published' && item.price !== null && item.price !== undefined ); // 清理 mediaItems 中的 URL,去除反引号和空格 // 同时处理 imageUrls 字段,将其转换为 mediaItems 格式 const cleanedGoods = filteredGoods.map(item => { // 首先清理 imageUrls 字段(如果存在) if (item.imageUrls && Array.isArray(item.imageUrls)) { item.imageUrls = item.imageUrls.map(url => { return url.trim().replace(/[`]/g, ''); }); // 如果没有 mediaItems 字段,将 imageUrls 转换为 mediaItems 格式 if (!item.mediaItems || !Array.isArray(item.mediaItems) || item.mediaItems.length === 0) { item.mediaItems = item.imageUrls.map(url => ({ type: 'image', url: url })); } } // 清理 mediaItems 中的 URL if (item.mediaItems && Array.isArray(item.mediaItems)) { item.mediaItems = item.mediaItems.map(media => { if (media.url) { // 去除 URL 中的反引号和空格 media.url = media.url.trim().replace(/[`]/g, ''); } return media; }); } return item; }); console.log('过滤后的商品列表:', cleanedGoods); // 检查商品数据结构 if (cleanedGoods.length > 0) { console.log('第一个商品的媒体数据:', cleanedGoods[0].mediaItems); } this.setData({ goods: cleanedGoods, loading: false }); }) .catch(err => { console.error('获取商品列表失败:', err); this.setData({ loading: false }); wx.showToast({ title: '获取商品失败,请稍后重试', icon: 'none' }); }); } });