3 Cách Lắng Sự Kiện Scroll Trong Vue 3

Lắng nghe sự kiện cuộn của các thành phần là một yêu cầu khá phổ biến. Dưới đây là 3 phương thức trong Vue 3 để lắng nghe sự kiện cuộn của thành phần.

1. Sử Dụng Bộ Lắng Nghe Sự Kiện: Event Listener

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
 
const container = ref()
const reachedBottom = ref(false)
 
const handleScroll = (event) => {
  const totalHeight = event.target.scrollHeight
  const currentPosition = event.target.scrollTop
  const visibleHeight = event.target.clientHeight
 
  if (currentPosition + visibleHeight >= totalHeight) {
    console.log('Đã đến cuối!')
    reachedBottom.value = true
  } else {
    reachedBottom.value = false
  }
}
 
onMounted(() => {
  container.value.addEventListener('scroll', handleScroll)
})
   
onUnmounted(() => {
  container.value.removeEventListener('scroll', handleScroll)
}) 
</script>
 
<template>
  <div ref="container">
    <p v-for="i in Array.from({length: 30}, (v, i) => i)">
      {{ i }}
    </p>
  </div>
  <div v-if="reachedBottom">Đã đến cuối</div>
</template>
 
<style>  
  #container {
    height: 200px; 
    overflow: auto; 
    border: 1px solid red; 
    padding: 0 10px;
  }
</style>

2. Sử Dụng Sự Kiện @scroll

Thêm sự kiện @scroll vào thành phần chứa.

<script setup>
  import { ref } from 'vue'
   
  const isAtBottom = ref(false)
   
  const processScroll = (e) => {
    const visibleArea = e.target.clientHeight
    const totalHeight = e.target.scrollHeight
    const scrollPosition = e.target.scrollTop
     
    if (scrollPosition + visibleArea >= totalHeight) {
      console.log('Đã đến cuối!')
      isAtBottom.value = true
    } else {
      isAtBottom.value = false
    }
  }
</script>
 
<template>
  <div @scroll="processScroll" id="content">
    <p v-for="i in Array.from({length: 30}, (v, i) => i)">
      {{ i }}
    </p>
  </div>
  <div v-if="isAtBottom">Đã đến cuối</div>
</template>
 
<style>  
  #content {
    height: 200px; 
    overflow: auto; 
    border: 1px solid red; 
    padding: 0 10px;
  }
</style>

3. Sử Dụng Thư Viện useScroll

Trước tiên, cài đặt gói @vueuse/core

Cách sử dụng theo tài liệu chính thức: useScroll

npm install @vueuse/core

Cách sử dụng trong thành phần:

<script setup>
import { ref, computed } from 'vue'
import { useScroll } from '@vueuse/core'
 
const scrollContainer = ref()
 
const { arrivedState } = useScroll(scrollContainer)
 
const isBottomReached = computed(() => {
  if (arrivedState.bottom) {
    console.log('Đã đến cuối!')
    return true
  }
 
  return false
})
</script>
 
<template>
  <div id="content" ref="scrollContainer">
    <p v-for="i in Array.from({ length: 30 }, (v, i) => i)">{{ i }}</p>
  </div>
  <div v-if="isBottomReached">Đã đến cuối</div>
</template>
 
<style>
#content {
  height: 200px;
  overflow: auto;
  border: 1px solid red;
  padding: 0 10px;
}
</style>

Thẻ: Vue3 scroll-events event-listeners vueuse JavaScript

Đăng vào ngày 27 tháng 6 lúc 19:04