网络编程
位置:首页>> 网络编程>> JavaScript>> vue 使用鼠标滚动加载数据的例子

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

作者:平常心_c  发布时间:2024-05-28 15:42:21 

标签:vue,鼠标滚动,加载数据

关于用鼠标滚动到某个位置我们就去加载数据,这样的场景与业务需求现在越来越常见,现在来分析下《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>

来源:https://blog.csdn.net/qq_37674616/article/details/83316070

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com