vue中使用防抖节流函数

防抖:触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间。
节流:高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率

防抖

在src下 新建utils,新建common.js

/*debounce*/
export function debounce(fn, delay = 1000) {
  let timer = null
  return function () {
    let args = arguments
    if (timer) {
      clearTimeout(timer)
      timer = null
    }
    timer = setTimeout(() => {
      fn.apply(this, args)// this 指向vue
    }, delay)
  }
}

使用


      
        
搜索
import { debounce } from '@/utils/common.js' methods:{ search:debounce(function () { console.log(this.message) },500) }
节流

在common.js

/*throttle*/
export function thorttle(fn, delay = 1000) {
  let lastTime = ''
  let timer = ''
  let interval = delay
  return function () {
    let args = arguments
    let nowTime = Date.now()
    if (lastTime && nowTime - lastTime < interval) {
      clearTimeout(timer)
      timer = setTimeout(() => {
        lastTime = nowTime
        fn.apply(this, args)
      }, interval)
    } else {
      lastTime = nowTime
      fn.apply(this, args)
    }
  }
}

使用


import { thorttle } from '@/utils/common.js'
methods:{
    search:thorttle(function () {
      console.log(this.messageInput)
    },1000)
  }

你可能感兴趣的:(vue中使用防抖节流函数)