vue列表下拉触底加载

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>列表触底加载</title>
		<style>
			#main{width:600px;margin:20px auto;line-height:30px;}
			#main img{margin: 10px 0;}
		</style>
	</head>
	<body>
		<div id="main">
			<div class="list">
				<div style="border: 1px solid #eee; padding:20px;" v-for="(item,index) in data" :key="index">
					<div>{{item.title}}</div>
					<img :src="item.img" alt="图片" width="200" height="100" />
					<div>{{item.body}}</div>
				</div>
			</div>
			<div style="text-align:center;">loading</div>
		</div>
		<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
		<script>
			window.onload = function(){
				new Vue({
				el: '#main',
				data: {
					name: '测试',
					data: [], // 列表数据
					page: 0, // 页数
					rows: 5, // 每页行数
					url: 'http://192.168.101:3000/list/page', // 请求列表的接口
					endScreen: false // 是否到屏幕底部,如果到屏幕底部则变为true
				},
				created(){
					this.getData();
					// 监听页面的滚动事件
					window.onscroll = ()=>{
						this.endScreen = this.screenCheck();
					}
				},
				watch: {
					// 监听屏幕是否到达底部,如果是,则增加页数,加载数据
					endScreen(newValue,oldValue){
						if(newValue){
							this.page++;
							setTimeout(()=>{
								this.getData(this.page, this.rows);
							},1000)
						}
					}
				},
				methods: {
					// 请求数据的方法
					getData(page = this.page, rows = this.rows){
						//fetch是新一代XMLHttpRequest的一种替代方案。无需安装其他库。可以在浏览器中直接提供其提供的api轻松与后台进行数据交互。
						fetch(this.url+'?page='+page+'&rows='+rows,{ method:'GET' }).then(res=>{
							console.log(res);
							return res.json(); //返回promise对象
						}).then(res=>{ // 真实数据
							console.log(res);
							for(let i in res.data){
								if(res.data[i].img){
									var reg = '127.0.0.1';
									res.data[i].img = res.data[i].img.replace(/127.0.0.1/g,'192.168.101'); // 注意跨域请求
								}
								this.data.push(res.data[i]);
							}
						})
					},
					// 检测屏幕是否到达底部的方法
					screenCheck(){
						let screenH = Math.ceil(window.innerHeight+window.scrollY); // 屏幕高度+滚动高度	
						let eleH = document.documentElement.offsetHeight; // 网页正文全文高
						return screenH === eleH;
					}
				}
			})
			}
		</script>
	</body>

</html>

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LLL_LH

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值