【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>
相关推荐
a11177623 分钟前
堆叠式流程图编辑器(html 开源)
开发语言·前端·javascript·开源·编辑器·html·流程图
兆子龙24 分钟前
前端必学:完美组件封装的 7 个原则
前端·javascript
兆子龙24 分钟前
ahooks useDebounce 与 useThrottle:防抖节流的最佳实践
java·javascript
兆子龙25 分钟前
React 性能坑:别让 AI 踩了,快来添加 rule 吧
前端·javascript
光影少年26 分钟前
Vue的生命周期有哪些及执行机制?
前端·vue.js·掘金·金石计划
来碗疙瘩汤28 分钟前
Vue 事件绑定完全指南:官方文档未详述的事件大全
前端·javascript·vue.js
天涯学馆28 分钟前
从 V8 引擎看 JS 代码是如何一步步变成机器指令的
前端·javascript·面试
new code Boy28 分钟前
JavaScript转Python”的速查表
开发语言·javascript·python
Elaine33629 分钟前
【通过 Vue 实例劫持突破 Web 编辑器的粘贴限制】
前端·javascript·vue.js·chrome devtools·前端逆向
zhensherlock31 分钟前
Protocol Launcher 系列:一键唤起 Windsurf 智能 IDE
javascript·ide·vscode·ai·typescript·github·ai编程