vue 监听页面滚动

发布于:2025-06-12 ⋅ 阅读:(16) ⋅ 点赞:(0)


一、全局监听页面滚动

在main.js或你的入口文件中添加一个全局的滚动事件监听器。

// 在 main.js 或入口文件中
app.config.globalProperties.$onScroll = function (callback) {
  window.addEventListener('scroll', callback);
};
 
app.config.globalProperties.$offScroll = function (callback) {
  window.removeEventListener('scroll', callback);
};

在组件中使用:

export default {
  mounted() {
    this.$onScroll(this.handleScroll);
  },
  beforeUnmount() {
    this.$offScroll(this.handleScroll);
  },
  methods: {
    handleScroll() {
      console.log('页面正在滚动');
      // 在这里编写你的滚动逻辑
    }
  }
}

二、组件内监听页面滚动

在单个组件内监听滚动事件,可以在该组件的mounted钩子中添加事件监听器,在beforeUnmount钩子中移除它,以避免内存泄漏。

export default {
  mounted() {
    window.addEventListener('scroll', this.handleScroll);
  },
  beforeUnmount() {
    window.removeEventListener('scroll', this.handleScroll);
  },
  methods: {
    handleScroll() {
      console.log('页面正在滚动');
      // 在这里编写你的滚动逻辑
    }
  }
}

注意事项:

防抖和节流:频繁的滚动事件可能会对性能产生影响,尤其是在移动设备上。使用lodash的_.throttle或_.debounce可以帮助减少这种情况的发生。例如,使用节流:

import _ from 'lodash';
 
export default {
  mounted() {
    this.handleScroll = _.throttle(this.handleScroll, 200); // 每200毫秒最多触发一次handleScroll函数
    window.addEventListener('scroll', this.handleScroll);
  },
  beforeUnmount() {
    window.removeEventListener('scroll', this.handleScroll);
  },
  methods: {
    handleScroll() {
      console.log('页面正在滚动');
      // 在这里编写你的滚动逻辑
    }
  }
}

使用Vue 3 Composition API:如果使用的是Vue 3,可以更灵活地使用Composition API,例如onMounted和onUnmounted钩子:

import { onMounted, onUnmounted } from 'vue';
import _ from 'lodash'; // 如果你需要防抖或节流功能的话
 
export default {
  setup() {
    const handleScroll = _.throttle(function() {
      console.log('页面正在滚动');
      // 在这里编写你的滚动逻辑
    }, 200); // 每200毫秒最多触发一次handleScroll函数(节流)
    
    onMounted(() => {
      window.addEventListener('scroll', handleScroll);
    });
    onUnmounted(() => {
      window.removeEventListener('scroll', handleScroll);
    });
  }
}