资料链接 scrolltab
实现楼层点击切换
需求
实现点击左侧一级,呈现右侧二三级的数据,要求需要很顺畅,不能卡顿现象
常规实现
- 实现: 遍历出需要一级的数据,通过点击一级将id传给二三级的数据接口,创建出
空数组
,通过创建销毁的过程不断将二三级的数据添加到空数组中 - 问题:此时会出现很卡顿现在,数据一直在加载中,但是
数据接口请求很快
,而前端渲染很慢
现象。 - 网友解决方法: 图片懒加载,虚拟列表
优化
- 问题发现:
- 在整个ui插件中可以看到,里面是for循环嵌套循环的,故我们创建的空数组,会出现点击一级,将空数组的数据添加到每一级里面,故一级如果有n个,那么空数组的数据就会同时在n个中出现,同时渲染出来,导致延迟
- 有图片的地方需要做懒加载处理
- 右侧如果滑动过快产生的问题
- 数据请求n遍后,是否考虑做缓存处理,减少多次请求
- 代码实现讲解
change(index) {
console.log('ScrollTab:---> index:' + index);
this.activeIndex = index;
if(index<6){//楼层的高度的索引,避免选中的一级没有在可视区域
document.querySelector('.yd-scrolltab-nav').scrollTop = 0;
} else {
document.querySelector('.yd-scrolltab-nav').scrollTop = (index-2)*50;
}
if(JSON.parse(sessionStorage.getItem('JsonArrs'))!=null){ //判断本地缓存中是否存在这个
if(JSON.parse(sessionStorage.getItem('JsonArrs'))[index].childer!=''){ //根据本地缓存中查看二三级的数组有没添加进去
} else {
var id = this.classifyList[index].id;
this._twoclassify(id,index);
}
} else {
var id = this.classifyList[index].id;
this._twoclassify(id,index);
}
},
_firstclassify(id,index){
cate_list({id: id}).then(res => {
if(res.code=='200'){
this.classifyList = res.data; //将一级数据先添加到空数组中
// console.log(JSON.stringify(this.classifyList));
for(var i = 0;i<this.classifyList.length;i++){
this.classifyList[i]['childer'] = ''
}
this._twoclassify(res.data[index].id,index) //请求二三级的数据
}
})
},
_twoclassify(id,index){
this.childer = [];
this.$dialog.loading.open('加载中');
cate2_list({id: id}).then(res => {
if(res.code=='200'){
this.$dialog.loading.close();
this.childer = res.data; //得到二三级的数据
this.JsonArr[index] = res.data; //组装成带key的数组数据childer
this.classifyList[index]['childer'] =JSON.parse( JSON.stringify(res.data)); //在一级的数据基础上动态添加新的数组对象
sessionStorage.setItem('JsonArrs',JSON.stringify(this.classifyList));//在值放到sessionStorage中(需要进行字符串转换,不然取不到数据)
this.JsonclassifyList = JSON.parse(sessionStorage.getItem('JsonArrs')) //转换回去,拿这个数据进行for遍历(重组后的数据)
}
})
},
代码重点
- 将原数据动态添加到JsonArr中,构建成带key的数组数据
this.JsonArr[index] = res.data
- 在原来的数组中动态添加childer进去到数组中
this.classifyList[index]['childer'] =JSON.parse(JSON.stringify(res.data))
- 重新构成2需要的数组,则可以进行遍历处理
sessionStorage.setItem('JsonArrs',JSON.stringify(this.classifyList));
this.JsonclassifyList = JSON.parse(sessionStorage.getItem('JsonArrs')); //新的数组