做状态判断,将需要缓存的组件缓存起来
```
//需要缓存的路由对象设置
{path:'/home',component:Home,meta:{keepAlive:true}},
```
## 12、下拉加载功能(按需加载数据)
**模拟接口设计**
- 默认后台每次给5条数据,前端告诉后台现在需要从第几条开始给
- 路径:/page?offset=5
- 后台返回还要告诉前端是否有更多的数据 hasMore:true
**功能介绍**
- 由于页面数据较多,第一次默认请求5条数据,当用户往下滑动距容器底部20px时再请求数据,这样往复请求,实现了按需加载,优化体验
**详细设计**
- 为需要添加滚动事件的dom添加ref属性方便获取``
- 判断何时加载数据
```
let{scrollTop,clientHeight,scrollHeight}=this.$refs.scroll;
if(scrollTop+clientHeight+20>scrollHeight){
//alert('hello')
this.getData() //获取更多图书数据
```
- 用定时器模拟滚动只触发一次,修复触发多次问题
```
loadMore(){
//触发scroll事件,可能触发n次 先进来开一个定时器,下一次触发将上次清除掉
clearTimeout(this.timer) //防抖
this.timer=setTimeout(()=>{
let{scrollTop,clientHeight,scrollHeight}=this.$refs.scroll;
if(scrollTop+clientHeight+20>scrollHeight){
//alert('hello')
this.getData() //获取更多图书数据
}
},300)
},
```
## 13、下拉刷新功能、
- vue中有插件vue-pull-refresh实现下拉加载,下拉刷新功能
- 原生实现
```
mounted(){
let scroll = this.$refs.scroll;//获取到要拖拽的元素
let top = scroll.offsetTop;//距最近定位父元素内壁距离35
let distance =0 ;//拉动距离默认为0
scroll.addEventListener('touchstart',(e) => {
//滚动条在最顶端时,并且当前盒子在顶端时候 才继续走
if (scroll.scrollTop !=0 || scroll.offsetTop != top) return;
let start = e.touches[0].pageY;//手指点击开发
let move = e=>{
let current = e.touches[0].pageY;
distance = current - start ;//求得拉动距离 负的不要
if (distance >0){
if(distance<=50){ //如果大于50了,认为就是50
scroll.style.top=distance + top+'px';
distance =distance
}else{
distance = 50;
scroll.style.top=top+50+'px';
}
}else {
////如果不在考虑范围内,移除move end 事件
scroll.removeEventListener('touchmove',move)
scroll.removeEventListener('touchend',end)
}
}
let end=e=>{
clearInterval(this.timer1)
this.timer1=setInterval(()=>{
if(distance>0){
distance -=1;
scroll.style.top=distance + top+'px';
}else{
clearInterval(this.timer1)
distance=0;
scroll.style.top=top+'px';
scroll.removeEventListener('touchmove',move)
scroll.removeEventListener('touchend',end)
//在这里刷新数据 vue中有插件vue-pull-refresh刷新
this.offset=0;//清除偏移量
this.books=[];
this.getData();
}
},5)
};
scroll.addEventListener('touchmove',move,false)
scroll.addEventListener('touchend',end,false)
},false)
},
```