Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to avoid WeChat Mini Programs's repeated jumps

2025-03-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

本篇内容主要讲解"微信小程序多次跳转的情况如何避免",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"微信小程序多次跳转的情况如何避免"吧!

场景在使用小程序的时候会出现这样一种情况:当网络条件差或卡顿的情况下,使用者会认为点击无效而进行多次点击,最后出现多次跳转页面的情况,这种情况要怎么避免。

解决办法

然后从 轻松理解JS函数节流和函数防抖 中找到了解决办法,就是函数节流(throttle):函数在一段时间内多次触发只会执行第一次,在这段时间结束前,不管触发多少次也不会执行函数。

/utils/util.js:

function throttle(fn, gapTime) {

if (gapTime == null || gapTime == undefined) {

gapTime = 1500

}

let _lastTime = null

return 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((new Date()).getSeconds())

}, 1000)

})

这样,疯狂点击按钮也只会1s触发一次。

但是这样的话出现一个问题,就是当你想要获取this.data得到的this是undefined, 或者想要获取微信组件button传递给点击函数的数据e也是undefined,所以throttle函数还需要做一点处理来使其能用在微信小程序的页面js里。

出现这种情况的原因是throttle返回的是一个新函数,已经不是最初的函数了。新函数包裹着原函数,所以组件button传递的参数是在新函数里。所以我们需要把这些参数传递给真正需要执行的函数fn。

最后的throttle函数如下:

function throttle(fn, gapTime) {

if (gapTime == null || gapTime == undefined) {

gapTime = 1500

}

let _lastTime = null

// 返回新的函数

return function () {

let _nowTime = + new Date()

if (_nowTime - _lastTime > gapTime || !_lastTime) {

fn.apply(this, arguments) //将this和参数传给原函数

_lastTime = _nowTime

}

}

}

再次点击按钮this和e都有了

到此,相信大家对"微信小程序多次跳转的情况如何避免"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report