前端vue滾動條滾動監(jiān)聽問題成功解決辦法
前言
前端處理滾動條滾動事件無非就是監(jiān)聽scroll事件,但是我們經(jīng)常會遇到 滾動事件頻繁觸發(fā), 無法正常獲取滾動的元素,最常見的就是 處理滾動位置
vueuse------useScroll的使用
安裝說明
vue3
npm i @vueuse/core --save
Vue2 的話還需要額外安裝 @vue/composition-api
npm i @vue/composition-api --save
useScroll的使用
1.在@vueuse/core包下引入useScroll
import { useScroll } from '@vueuse/core'
<!--需要滾動的容器--> <div id="container" ref="container" class="container"></div>
<!--第一個參數(shù)el(需要滾動的容器)--> this.$nextTick(() => { const { x, y, isScrolling, arrivedState, directions } = useScroll(document.getElementById('container')) this.x = x this.y = y this.isScrolling = isScrolling this.arrivedState = arrivedState this.directions = directions }) <!-- x:用于記錄上次滾動的scrollLeft的值, y:記錄上次滾動的scrollTop的值, isScrolling: 表示是否正在滾動, arrivedState: {top/right/bottom/left}表示滾動條是否到達(dá)指定邊界, directions: {top/right/bottom/left} 表示滾動條正在滾動的方向 -->
<!--第二個參數(shù),可以設(shè)置偏移量offset(滾動條到達(dá)上下左右邊界的一個偏移值,例如left設(shè)置為30, 則水平滾動條距離左邊界30px時則認(rèn)為到達(dá)了左邊界)--> const { x, y, isScrolling, arrivedState, directions } = useScroll(document.getElementById('container'), { offset: { top: 0, bottom: 300, right: 30, left: 0 }})
<!--第二個參數(shù),{behavior: smooth}設(shè)置平滑的滾動--> const { x, y, isScrolling, arrivedState, directions } = useScroll(document.getElementById('container'), { behavior: 'smooth' })
2.可以手動設(shè)置滾動位置
3.這個方法也提供自定義指令的方式
自定義指令vScroll在@vueuse/components中
import { vScroll } from '@vueuse/components' Vue.directive('scroll', vScroll) <div id="container" ref="container" v-scroll="onScroll" class="container"></div> onScroll({ x, y, isScrolling, arrivedState, directions }) { this.x = x this.y = y this.isScrolling = isScrolling this.arrivedState = arrivedState this.directions = directions }
4.場景
1.滾動到底部,出現(xiàn)‘返回頂部’按鈕
2.滾動到底部,加載新數(shù)據(jù)
3.其他
總結(jié)
到此這篇關(guān)于前端vue滾動條滾動監(jiān)聽問題成功解決的文章就介紹到這了,更多相關(guān)前端vue滾動條滾動監(jiān)聽內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue-cli解決IE瀏覽器sockjs-client錯誤方法
這篇文章主要為大家介紹了vue-cli解決IE瀏覽器sockjs-client錯誤方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08vue3如何添加eslint校驗(eslint-plugin-vue)
這篇文章主要介紹了vue3如何添加eslint校驗(eslint-plugin-vue),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01完美解決vue引入BMapGL is not defined的問題
在Vue項目中使用BMapGL時,通過在src下添加bmp.js文件并配置密鑰(ak),可以有效解決地圖API的應(yīng)用問題,本方法是基于個人經(jīng)驗總結(jié),希望能為開發(fā)者提供參考和幫助2024-10-10