You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

153 lines
3.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

// pages/index/index.js
const { get } = require('../../utils/request');
Page({
/**
* 页面的初始数据
*/
data: {
productList: [], // 商品列表数据
loading: false, // 加载状态
hasError: false, // 错误状态
errorMsg: '' // 错误消息
},
/**
* 生命周期函数--监听页面加载
*/
onLoad(options) {
// 页面加载时获取商品列表
this.getProductList();
},
/**
* 获取商品列表
*/
async getProductList() {
try {
// 设置加载状态
this.setData({
loading: true,
hasError: false
});
// 调用API获取商品列表
const response = await get('/api/products');
// 根据实际返回的数据结构调整 - 从 products 字段中提取数据
let productList = response.products || [];
// 处理商品数据确保图片URL正确
productList = productList.map(item => {
// 根据实际后端返回的数据结构优先使用已有的imageUrl否则尝试其他可能的图片字段
let processedImageUrl = item.imageUrl || item.image || item.img || item.pic || item.picture || '';
// 如果图片URL是相对路径拼接基础URL
if (processedImageUrl && !processedImageUrl.startsWith('http')) {
if (processedImageUrl.startsWith('/')) {
processedImageUrl = `http://localhost:3000${processedImageUrl}`;
} else {
processedImageUrl = `http://localhost:3000/${processedImageUrl}`;
}
}
return {
...item,
imageUrl: processedImageUrl
};
});
// 更新页面数据
this.setData({
productList: Array.isArray(productList) ? productList : [],
loading: false
});
console.log('商品列表获取成功:', productList);
} catch (error) {
console.error('获取商品列表失败:', error);
this.setData({
hasError: true,
errorMsg: error.message || '获取商品列表失败',
loading: false
});
}
},
/**
* 处理商品点击事件
*/
onProductTap(e) {
const product = e.currentTarget.dataset.product;
console.log('点击了商品:', product);
// 这里可以跳转到商品详情页
// wx.navigateTo({
// url: `/pages/product/detail?id=${product.id}`
// });
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {
},
/**
* 生命周期函数--监听页面显示
*/
onShow() {
// 页面显示时重新获取商品列表
// this.getProductList();
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {
// 下拉刷新时重新获取商品列表
this.getProductList().finally(() => {
wx.stopPullDownRefresh(); // 停止下拉刷新动画
});
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {
// 这里可以实现分页加载更多商品
console.log('滚动到底部');
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {
}
})