throttleHook Vue 节流值 hook

2020-04-09 11:47:13 浏览数 (1)

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

    <div>
      <Card style='margin: 20% auto; width: 600px' title=''>
        <h2> {{ state.name }} </h2>
        <div> default:  {{ state.age }} </div>
        <div> throttle: {{ info }} </div>
        <Button @click='add' > add </Button>
      </Card>
    </div>
    
  </div>
</template>

<script>
import { reactive } from '@vue/composition-api'
import throttleHook from '@/hooks/throttleHook'


export default {

  setup(){
    const state = reactive({name: 'jeck', age: 23})
    const add = () => state.age  = 1
    const [ info ] = throttleHook(() => state.age, 1000)

   return {
     add,
     state,
     info,
   }

  }

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


/**
 * 节流值hook 
 * @param { Function } watchFn 观察函数 
 * @param { Number } wait 时间间隔 ms 
 * @return { [ state, setState ] } state 间隔数据, setState 节流函数
 * @example
 * 
 * const count = ref(1)
 * const add = () => count.value  = 1
 * const [ state ] = throttleHook(() => count.value)
 * 
 */
export default function throttleHook(watchFn, wait){

    const state = ref(watchFn())
    const { run: setState } = throttleFnHook(data => state.value = data, wait)
    watch(watchFn, (val) => setState(val) )

    return [ state, setState ]
}

0 人点赞