Vue 监听关键字进行查询,并进行防抖与节流操作

在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
      })
    },
  }

 

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值