本篇文章給大家介紹一下小程序使用函數(shù)節(jié)流解決頁(yè)面多次跳轉(zhuǎn)問(wèn)題。有一定的參考價(jià)值,有需要的朋友可以參考一下,希望對(duì)大家有所幫助。
在使用小程序的時(shí)候會(huì)出現(xiàn)這樣一種情況:當(dāng)網(wǎng)絡(luò)條件差或卡頓的情況下,使用者會(huì)認(rèn)為點(diǎn)擊無(wú)效而進(jìn)行多次點(diǎn)擊,最后出現(xiàn)多次跳轉(zhuǎn)頁(yè)面的情況,這個(gè)問(wèn)題可以通過(guò)JS中的函數(shù)節(jié)流和函數(shù)防抖找到解決方法。
根據(jù)官方文檔介紹,函數(shù)節(jié)流就是規(guī)定一個(gè)單位時(shí)間,在這個(gè)單位時(shí)間內(nèi),只能有一次觸發(fā)事件的回調(diào)函數(shù)執(zhí)行,如果在同一個(gè)單位時(shí)間內(nèi)某事件被觸發(fā)多次,只有一次能生效。因此修改.js文件如下:
function throttle(fn, gapTime) { if (gapTime == null|| gapTime == undefined) { gapTime = 1500 } let _lastTime = nullreturn function () { let _nowTime = +new Date() if (_nowTime -_lastTime > gapTime || !_lastTime) { fn() _lastTime =_nowTime } } } module.exports = { throttle: throttle } /pages/throttle/throttle.wxml: tap /pages/throttle/throttle.js const util = require('../../utils/util.js') Page({ data: { text: 'tomfriwel' }, onLoad: function (options) { }, tap:util.throttle(function (e) { console.log(this) console.log(e) console.log((newDate()).getSeconds()) }, 1000) })
這樣,瘋狂點(diǎn)擊按鈕也只會(huì)1s觸發(fā)一次。
但是這樣的話出現(xiàn)一個(gè)問(wèn)題,就是當(dāng)你想要獲取this.data得到的this是undefined, 或者想要獲取微信組件button傳遞給點(diǎn)擊函數(shù)的數(shù)據(jù)e也是undefined,所以throttle函數(shù)還需要做一點(diǎn)處理來(lái)使其能用在微信小程序的頁(yè)面js里。
出現(xiàn)這種情況的原因是throttle返回的是一個(gè)新函數(shù),已經(jīng)不是最初的函數(shù)了。新函數(shù)包裹著原函數(shù),所以組件button傳遞的參數(shù)是在新函數(shù)里。所以我們需要把這些參數(shù)傳遞給真正需要執(zhí)行的函數(shù)fn。
最后的throttle函數(shù)如下:
function throttle(fn, gapTime) { if (gapTime == null|| gapTime == undefined) { gapTime = 1500 } let _lastTime = null// 返回新的函數(shù) return function () { let _nowTime = +new Date() if (_nowTime -_lastTime > gapTime || !_lastTime) { fn.apply(this, arguments) //將this和參數(shù)傳給原函數(shù) _lastTime =_nowTime } } }
再次點(diǎn)擊按鈕this和e都有了:
推薦:《小程序開發(fā)教程》