触底加载更多(原理 + 在vue中的使用)

触底加载更多(原理)

理解
	1.使用api分别获取
		滚动高度(document.documentElement.scrollTop)
	 	可视区域/屏幕高度(document.documentElement.clientHeight)
	 	页面高度(document.documentElement.scrollHeight)

	2.原理 :If(滚动高度 + 可视区域  >= 页面高度){ do something函数}
vue中的应用

1.用事件监听,监听你要执行的事件
        window.addEventListener(‘scroll’, 你要执行的事件)

2.取消事件监听,监听你要执行的事件
        window.removeEventListener(‘scroll’, 你要执行的事件,false)

一定要取消事件监听!不然你执行完这个事件它也会到其他页面继续执行这个事件。

例子

  data: function() {
    return {
		 group:[], //返回数据
		 page:1,	//加载页数
	};
  },
  mounted() {
	  //事件监听
	  window.addEventListener('scroll', this.listenBottomOut)
	  //预先加载一遍
	  getGroulp(1).then(res =>{
		  this.$set(this,"group",res.data)
	  })
  },
  
  //vue 的生命周期钩子函数
  methods: {
		//触底触发函数
		listenBottomOut () { 
			let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            let clientHeight = document.documentElement.clientHeight;
            let scrollHeight = document.documentElement.scrollHeight;
			if (scrollTop + clientHeight >= scrollHeight) { 
				if(this.group.length === 10){
					getGroulp(this.page + 1).then(res =>{
						  var groups = this.group.concat(res.data) 
						  this.$set(this,"group",groups)
					  })
				}
            }
		},
			
	
  },
   //vue 的生命周期钩子函数
  destroyed(){
	  //离开页面取消监听
	  window.removeEventListener('scroll', this.listenBottomOut,false) 
  }
  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 实现触底加载可以通过监听滚动事件,当滚动到页面底部时触发加载更多的操作。下面是一个简单的实现: 首先在模板添加一个滚动容器及一个列表,代码如下: ``` <template> <div class="scroll-container" ref="scrollContainer" @scroll="handleScroll"> <ul> <li v-for="item in items" :key="item.id">{{ item.text }}</li> </ul> </div> </template> ``` 然后在 `data` 定义需要加载的数据、当前页数和每页的条数等相关数据: ``` <script> export default { data() { return { items: [], // 需要加载的数据 currentPage: 1, // 当前页数 pageSize: 10, // 每页的条数 total: 0 // 数据总数 }; }, methods: { // 加载更多数据 loadMore() { // 模拟异步加载数据 setTimeout(() => { for (let i = 0; i < this.pageSize; i++) { this.items.push({ id: this.total + i + 1, text: `item ${this.total + i + 1}` }); } this.total += this.pageSize; this.currentPage++; }, 1000); }, // 监听滚动事件 handleScroll() { const scrollContainer = this.$refs.scrollContainer; const scrollHeight = scrollContainer.scrollHeight; const scrollTop = scrollContainer.scrollTop; const clientHeight = scrollContainer.clientHeight; if (scrollHeight - scrollTop === clientHeight) { this.loadMore(); } } } }; </script> ``` 在 `handleScroll` 方法,判断当前滚动容器的滚动高度和可视区域的高度是否相等,如果相等则触发加载更多的操作。 最后需要注意的是,为了确保第一次进入页面时也能触发加载操作,需要在 `mounted` 钩子函数手动触发一次 `loadMore` 方法: ``` mounted() { this.loadMore(); } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值