在utils下新建debounce.js 代码如下:
/**
* 函数防抖 (只执行最后一次点击)
* @param fn
* @param delay
* @returns {Function}
* @constructor
*/
export const Debounce = (fn, t) => {
const delay = t || 500
let timer
return function() {
const args = arguments
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
timer = null
fn.apply(this, args)
}, delay)
}
}
/**
* 函数节流
* @param fn
* @param interval
* @returns {Function}
* @constructor
*/
export const Throttle = (fn, t) => {
let last
let timer
const interval = t || 500
return function() {
const args = arguments
const now = +new Date()
if (last && now - last < interval) {
clearTimeout(timer)
timer = setTimeout(() => {
last = now
fn.apply(this, args)
}, interval)
} else {
last = now
fn.apply(this, args)
}
}
}
在需要使用的页面引入(这里以防抖作为示例)
import { Debounce } from '@/utils/debounce'
具体使用:
// 模糊搜索
watch: {
// 如果 `formName` 发生改变,这个函数就会运行
formName: function(newQuestion, oldQuestion) {
this.debouncednewFormName()
}
},
created: function() {
// `debounce` 是一个限制操作频率的函数。防抖操作,在0.5秒内连续更改数据不进行查询
this.debouncednewFormName = Debounce(this.newFormName, 500)
},
mounted() {
this.newFormName() // 数据初始化
},
methods: {
newFormName() {
this.loading = true
this.formName = this.formName.trim()
var data = { name: this.formName, sortName: this.sortName, sortType: this.sortType }
newFormName(data).then((data) => {
this.formData = data
for (var i in this.formData) {
this.formData[i].startTime = this.formData[i].startTime.substr(0, 10) // 将时间格式化
this.formData[i].endTime = this.formData[i].endTime.substr(0, 10) // 将时间格式化
}
this.loading = false
})
},
}