JavaScript

超轻量级php框架startmvc

vue 使用鼠标滚动加载数据的例子

更新时间:2020-09-20 05:18:01 作者:startmvc
关于用鼠标滚动到某个位置我们就去加载数据,这样的场景与业务需求现在越来越常见,现

关于用鼠标滚动到某个位置我们就去加载数据,这样的场景与业务需求现在越来越常见,现在来分析下《vue.js 实战》中作者的一个解决策略:

1. 设置一个标志位用来判断数据是否在加载中

2. 将滚动区域设置成 overfow:auto(显示滚动条)

3. 给滚动区域加入监听事件并绑定ref属性 来获取DOM实例

4. 当鼠标滚动到底部时,加载数据

4.1 如果此时 标志位为true则 直接退出,不进行此时数据加载

关键代码如下:


<template>
 //...代码省略
//该div 为要滚动区域
<div class="daily-list" ref="list" @scroll="handleScroll">
 // ...
</div>
</template>
<script>
 export default{
 data(){
 return {
 recommendList:[], //存放滚动区域要显示的数据
 isLoading:false //默认没有在加载数据
 }
 },
 methods:{
 //获取数据
 getRecommendList(){
 //表示正在加载数据
 this.isLoading=true;
 $.ajax.get('news/before/'+preDay).then(res=>{
 this.recommendList.push(res);
 //数据请求完成
 this.isLoading=false;
 })
 },
 handleScroll(){
 const $list=this.$refs.list;
 //如果数据有在加载中则这次请求退出
 if(this.isLoading) return; 
 //已经滚动的距离加页面的高度等于整个内容区高度时,视为接触到底部 
 //scrollTop 获取到顶部的滚动距离
 // clientHeight 表示页面视口高度
 // scrollHeight 页面内容的高度 
 if($list.scrollTop+document.body.clientHeight>=$list.scrollHeight){
 this.getRecommendList();
 }
 }
 },
 mounted(){
 this.getRecommendList()
 }
}
</script>
<style>
 width: 300px;
 position: fixed;
 top:0;
 left: 150px;
 //出现滚动条
 overflow: auto;
</style>

以上这篇vue 使用鼠标滚动加载数据的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

vue 鼠标滚动 加载数据