小程序开发中使用节流函数throttle的正确方式

问题

以前在开发小程序项目时,经常遇到节流需求,然后研究了好久都没成功。今天又遇到了,终于被我弄成功了。原来是使用方法错误,终究还是Javascript的基本功差导致的。

使用的小程序开发框架是mpvueuniapp

试错历程

做了很多尝试都没成功,但我觉得我这些错误的尝试方法有助于帮助我去理解这个问题,就记录下。

1. 试错案例一
<template>
	<input type="digit" @input="onInput" />
<template>

<script>
import _lodash from '@/utils/myLodash'

export default {
	data() {
		value: { input: '' }
	},
	methods: {
		onInput(e) {
			_loadash.throttle(() => {
				this.$set(this.value, 'input', e.value)
			}, 1000)
		}
	}
}
</script>

这样的写法是无效的,后面研究了许久,其实节流函数throttle本身就会返回一个匿名函数,所以就知道这种写法无效的原因了,尝试改进。

2. 试错案例二
<template>
	<input type="digit" @input="onInput" />
<template>

<script>
import _lodash from '@/utils/myLodash'

export default {
	data() {
		value: { input: '' }
	},
	methods: {
		onInput: _lodash.throttle(e => {
			this.$set(this.value, 'input', e.value)
		}, 1000)
	}
}
</script>

经过这一番改进后,节流函数确实生效了,但是又出现了新的问题,会报如下错误:
TypeError: _this.$set is not a function

看到这个错误的时候我就知道这是this绑定的作用域错误的问题导致的。后面我去翻看Lodash源码发现throttle函数有对我传入的回调函数进行apply(绑定作用域)处理:

源码:result = func.apply(thisArg, args)// func就是我们传入的回调函数

此时我就明白了,箭头函数使用apply是无效的,然后我把箭头函数改成了匿名函数就可以了。

想了解this作用域问题的朋友可以参考我的另一篇文章:《ES5中,this永远指向最后调用它的那个对象》

注意: Vue官方文档中有提示methods中的函数不能使用箭头函数

最终解决方法
<template>
	<input type="digit" @input="onInput" />
<template>

<script>
import _lodash from '@/utils/myLodash'

export default {
	data() {
		value: { input: '' }
	},
	methods: {
		onInput: _lodash.throttle(function(e) {
			this.$set(this.value, 'input', e.value)
		}, 1000)
	}
}
</script>
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值