debounceFnHook vue函数防抖hook

2020-04-09 11:46:37 浏览数 (1)

使用例子
代码语言:javascript复制
<template>
  <div class="home">

    <div>
      <Card style='margin: 20% auto; width: 600px' title='form'>
        <h4> {{state}} </h4>
        <Input  :value='state' @input='run'  />
      </Card>
    </div>
    
  </div>
</template>

<script>
// import { ref } from '@vue/composition-api'
import debounceFnHook from '@/hooks/debounceFnHook'
import setRefHook from '@/hooks/setRefHook'

export default {

  setup(){
    const [ state, setState ] = setRefHook('')
    const { run, cancel } = debounceFnHook( setState, 500 )

   return {
     state,
     run,
     cancel
   }

  }

}
</script>
实现
代码语言:javascript复制
import { ref } from '@vue/composition-api'


/**
 * 函数防抖处理
 * @param { Function } fn 被包装函数 
 * @param { Number } wait 等待时间 ms 
 * @return { { run, cancel } } run 包装后的执行函数  cancel 取消执行
 * @exports
 * 
 *  const [ state, setState ] = setRefHook('')
    const { run, cancel } = debounceFnHook( setState, 500 )
 *  
 */
export default function debounceFnHook(fn, wait){
    const timer = ref(null)
    
    const cancel = () => timer.value&&clearTimeout(timer.value)

    const run = (...args) => {
        cancel()
        timer.value = setTimeout(() => fn(...args), wait)
    }

    return {
        run,
        cancel
    }
}

0 人点赞