首页 > 解决方案 > 在 vue.js 中检测滚动

问题描述

我想在检测到滚动时在 vue.js 中触发一个函数,或者在滚动超过窗口大小的 5% 或类似的东西时更好地触发一个函数。但我无法做到正确。

这是我的代码:

<template>
  <div>
    <Test1 v-on:scroll.passive="handleScroll"></Test1>
  </div>
</template>

<script>
import Test1 from "./Test1";

export default {
  name: "HomePage",
  components: {
    Test1
  },
  methods: {
    handleScroll: function() {
      alert("something");
    }
  }
};
</script>

<style >
</style> 



标签: javascripteventsvue.jsmethods

解决方案


您可以使用滚动事件并在需要时触发您的功能

    window.addEventListener('scroll', function(e){
        if(e.pageY>window.innerHeight*0.05){
            console.log('over 5%'); //use your function here
        }
    });

确保在不再需要事件侦听器或卸载组件时删除它


推荐阅读