vue——监听滚动事件

注意第三个参数选择 true ,是因为滚动事件是捕获事件而不是冒泡事件

  • 监听滚动事件
    mounted () {
      window.addEventListener('scroll', this.scroll, true)
    },
  • 所触发的事件
    methods: {
      scroll () {
      	// 获取元素对屏幕上边的距离
        let top = parseInt(this.$refs.news[this.$refs.news.length - 1].getBoundingClientRect().top)
        if (top < 500) {
          // 节流
          clearTimeout(this.timer)
          this.timer = setTimeout(() => {
            console.log('hello world!')
          }, 400)
        }
      }
	}
  • 销毁监听
    destroyed () {
      window.removeEventListener('scroll', this.scroll, true)
    }

你可能感兴趣的:(vue)