参考:https://www.bilibili.com/video/BV1RK4y1v7zv?p=19&spm_id_from=pageDriver

import { request } from "../../request/index.js"; //必须全路径
Page({
/**
* 页面的初始数据
*/
data: {
leftMenuList:[],
rightMenuList:[],
//当前选中的菜单索引
currentIndex:0
},
//接口返回数据
Cates:[],
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
/*
web 和 微信小程序中的本地存储的区别:
1.读取和设置的时候区别
web: localStorage.setItem("key","value") localStorage.getItem("key")
小程序:wx.setStorageSync("key","value"); wx.getStorageSync("key");
2.存储的时候区别
web中存储的不管是什么类型的数据,读取的时候都先转换成字符串类型,再存储进去
小程序:不存在数据转换过程
*/
//this.getCates();
//加载的时候先判断本地有没有缓存,如果有缓存而且没有过期,就用缓存的数据来加载页面。
//先判断一下本地存储中 有没有旧的数据
//{time:Date.now(),data:[...]}
//没有旧数据,直接网络请求
//有旧数据而且没有过期,就使用旧数据加载
const Cates = wx.getStorageSync('cates');//这里的key用cates
if(!Cates)
{//不存在就请求数据
this.getCates();
}
else
{
if(Date.now() - Cates.time > 60 * 60 * 1000)
{
this.getCates(); //如果数据缓存超过1小时,重新加载网络数据
}
else
{
this.Cates = Cates.data;
console.log("加载数据:");
console.log(this.Cates);
//给左侧和右侧数据整理
let leftMenuList = this.Cates.map(v => v.cat_name);
let rightMenuList = this.Cates[0].children;
//加载页面数据
this.setData({
leftMenuList,
rightMenuList
})
}
}
},
getCates() {
request({ url:"https://api-hmugo-web.itheima.net/api/public/v1/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 rightMenuList = this.Cates[0].children;
//加载页面数据
this.setData({
leftMenuList,
rightMenuList
})
})
},
//左侧菜单的点击事件
menuClick(e){
let _index = e.currentTarget.dataset.index;
//构造左侧的大菜单数据
let rightMenuList1 = this.Cates[_index].children;
//更新数据
this.setData({
rightMenuList: rightMenuList1,
currentIndex : _index
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})
浙公网安备 33010602011771号