版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fifteen718/article/details/85205817
为限制输入框change事件疯狂发送查询请求,此时我们就需要用一个节流函数来优化一下性能了。
大致思路:设置一个定时器,在指定时间间隔内运行代码时重置定时器,直到函数请求停止,函数才会在限定时间之后才会正式执行。
实际项目中,将节流函数挂载到vue原型上,方便调用,例 main.js 中:
// 写一个节流函数
Vue.prototype.$throttle = (method) => {
clearTimeout(method.tId)
method.tId = setTimeout(function() {
method()
}, 500)
}
当某个页面需要用到它时,例 area-select.vue 中:
filterMethod(key) {
this.searchValue = key
this.$throttle(this.listMerIndex)
},
listMerIndex() {
this.areas = null
this.searchValue = this.searchValue.trim()
if (!this.searchValue) {
return false
}
let data = {
merRole: 5,
realName: this.searchValue
}
this.queryCancel && this.queryCancel()
this.$apis.listMerIndex(data, this, 'queryCancel').then((res) => {
this.areas = res.data
}).catch((error) => {
this.$message({
showClose: true,
type: 'error',
message: error.message
})
})
}
参考链接:js函数节流