分类页面预览图:
分类页面主要代码
index.js
// pages/category/index.js
import {
request
} from "../../request/index.js"
Page({
/**
* 页面的初始数据
*/
data: {
//左侧菜单数据
leftMenuList: [],
//右侧的商品数据
rightContent: [],
// 被点击的左侧菜单
currentIndex: 0,
//右侧距离顶部距离
scrollTop:0,
},
//接口返回数据
Cates: [],
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
/**
* 1,先判断本地储存中有没有旧的缓存数据
* 本地存储数据格式:
* {time.Data.now(),data:[.....]}
* 2,没有数据就发送请求,
* 3,有旧数据且旧数据没有过期,直接使用本地储存中的旧数据
*/
const Cates = wx.getStorageSync("cates");
if (!Cates) {
//不存在,获取数据
this.getCates();
} else {
//本地有缓存
if (Date.now() - Cates.time > 1000 * 10) {
//超过10s就重新发送请求
this.getCates();
} else {
//可以使用本地缓存数据
this.Cates = Cates.data;
//构造左侧菜单数据
let leftMenuList = this.Cates.map(v => v.cat_name);
//构造右侧商品数据
let rightContent = this.Cates[0].children;
this.setData({
leftMenuList,
rightContent,
})
}
}
},
//获取分类数据
getCates() {
request({
url: "/categories"
}).then(res => {
this.Cates = res.data.message;
//把结构数据存入本地缓存
wx.setStorageSync('cates', {
time: Date.now(),
data: this.Cates
});
//构造左侧菜单数据
let leftMenuList = this.Cates.map(v => v.cat_name);
//构造右侧商品数据
let rightContent = this.Cates[0].children;
this.setData({
leftMenuList,
rightContent,
})
})
},
//左侧菜单的点击事件
handleItemTap(e) {
/*
1,获取被点击菜单的索引
2,给data中的currentIndex赋值
3,根据不同索引渲染右侧内容
*/
const {
index
} = e.currentTarget.dataset;
let rightContent = this.Cates[index].children;
this.setData({
currentIndex: index,
rightContent,
//设置右侧距离顶部距离
scrollTop:0,
});
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})