【vue 监听页面滑动到底部】

监听页面滑动到底部

IntersectionObserver

在 Vue 中监听触底可以通过使用IntersectionObserver实现。IntersectionObserver是一个可以异步观察目标元素与其祖先或视窗交叉状态的API。当目标元素进入或退出视口时,会触发IntersectionObserver的回调函数。

以下是一个监听触底的示例:

vue 复制代码
<template>
  <div class="container" ref="container">
    <!-- 这里是数据列表 -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      observer: null,
    }
  },
  mounted() {
    // 创建 IntersectionObserver 实例
    this.observer = new IntersectionObserver(this.handleObserve, {
      root: null,
      rootMargin: '0px',
      threshold: 1.0,
    });
    // 监听容器底部
    this.observer.observe(this.$refs.container.lastChild);
  },
  methods: {
    handleObserve(entries) {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          // 滚动到底部触发加载更多
          this.loadMoreData();
        }
      });
    },
    loadMoreData() {
      // 加载更多数据的逻辑
    },
  },
};
</script>

在mounted钩子函数中创建IntersectionObserver实例,并监听容器底部的元素。在handleObserve回调函数中判断当前元素是否可见,如果可见则触发加载更多数据的逻辑。

scroll 事件监听器

在 Vue 中监听页面滑动到底部的方法如下:

  1. 创建一个 scroll 事件监听器,并将事件绑定在根元素上(windowdocument.body)。
js 复制代码
mounted() {
  window.addEventListener('scroll', this.handleScroll)
}
  1. 在事件处理函数 handleScroll 中,判断页面滚动到底部的条件,如果条件成立,执行自定义事件 scroll-to-bottom
js 复制代码
methods: {
  handleScroll() {
    const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
    const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
    const clientHeight = document.documentElement.clientHeight || window.innerHeight
    if (scrollTop + clientHeight >= scrollHeight) {
      this.$emit('scroll-to-bottom')
    }
  }
}
  1. 在需要监听滚动到底部的组件中,使用 $on 方法监听自定义事件 scroll-to-bottom,并执行相应的操作。
html 复制代码
<template>
  <div>
    <div v-for="item in list" :key="item.id">{{ item.text }}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      list: []
    }
  },
  mounted() {
    this.loadMore()
    this.$on('scroll-to-bottom', this.loadMore)
  },
  methods: {
    loadMore() {
      // TODO: 加载更多数据
    }
  }
}
</script>
相关推荐
像风一样自由20202 小时前
HTML与JavaScript:构建动态交互式Web页面的基石
前端·javascript·html
浪裡遊3 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
幽络源小助理3 小时前
SpringBoot基于Mysql的商业辅助决策系统设计与实现
java·vue.js·spring boot·后端·mysql·spring
Liudef065 小时前
2048小游戏实现
javascript·css·css3
鱼樱前端6 小时前
今天介绍下最新更新的Vite7
前端·vue.js
独立开阀者_FwtCoder7 小时前
【Augment】 Augment技巧之 Rewrite Prompt(重写提示) 有神奇的魔法
前端·javascript·github
我想说一句7 小时前
事件机制与委托:从冒泡捕获到高效编程的奇妙之旅
前端·javascript
汤姆Tom7 小时前
JavaScript reduce()函数详解
javascript
小飞悟7 小时前
你以为 React 的事件很简单?错了,它暗藏玄机!
前端·javascript·面试
中微子7 小时前
JavaScript 事件机制:捕获、冒泡与事件委托详解
前端·javascript