throttleFnHook Vue 函数节流Hook

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

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

    <div>
      <Card style='margin: 20% auto; width: 600px' title='form'>
        <h4> {{state}} </h4>
        <Button @click="run"> add </Button>
      </Card>
    </div>
    
  </div>
</template>

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

export default {

  setup(){
    const [state, setState] = setRefHook(0)
    const { run, cancel } = throttleFnHook( () => setState(state.value   1) , 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 = 1
 * const addOne = () => state = state   1
 * const { run: addOne } = throttleFnHook(addOne, 500) 
 * 
 */
export default function throttleFnHook(fn, wait){

    const timer = ref(null)

    const cancel = () => timer.value&&clearTimeout(timer.value)

    const run = (...args) => {
        if(timer.value){return}
        
        timer.value = setTimeout(() => {

            fn(...args)
            timer.value = null
            
        }, wait)
    }
    
    return {
        cancel,
        run
    }
}

0 人点赞