最近有这样的一个应用场景,input
输入框中监听用户输入,变化了就发送ajax
请求后端数据,以前搜索筛选都是用户手动点击或者回车,现在实时获取,想着最好还是做下节流
lodash官网
吐槽一下,lodash这个文档写的真拉胯,按它的示例,我饭碗早就没了…
1. 无效的示例(会出错)
methods:{
handleFilterTags1(e) {
_.throttle(() => {
this.ajaxGetTagsAggregation(e);
}, 200);
},
handleFilterTags2(e) {
_.throttle(this.ajaxGetTagsAggregation(e), 200);
},
}
handleFilterTags1
中 ajaxGetTagsAggregation方法不会预期执行。
handleFilterTags2
中控制台会警告和报错
但是ajaxGetTagsAggregation能正常执行
看了下源码,应该是返回了一个函数
盲猜应该是this指向问题
2.我研究调试成功的写法
methods:{
// 方式1,唯一的好处就是可以访问Vue全局挂载的lodash
handleFilterTags(e) {
_.throttle(function filterTags() {
console.log('调用了---', e, this);
const params = e ? {
tag_name: e.trim() } : {
};
this.ajaxGetTagsAggregation(params);
}, 300).call(this);
},
// 方式2, 不用自己修改this指向
handleFilterTags2: _.throttle(function filterTags(e) {
const params = e ? {
tag_name: e.trim() } : {
};
this.ajaxGetTagsAggregation(params);
}, 300),
}
throttle还是尽量不要用箭头函数了
3.其它场景
mounted() {
window.addEventListener('scroll', _.throttle(this.scrollBottom, 300));
},