debounceHook Vue 防抖值 hook
2020-04-05 本文已影响0人
copyLeft
使用例子
<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'
import debounceHook from '@/hooks/debounceHook'
export default {
setup(){
const state = reactive({name: 'jeck', age: 23})
const add = () => state.age += 1
const [ info ] = debounceHook(() => state.age, 1000)
return {
add,
state,
info,
}
}
}
</script>
实现
import { ref, watch } from '@vue/composition-api'
import debounceFnHook from './debounceFnHook.js'
/**
* 防抖值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 ] = debounceHook(() => count.value)
*
*/
export default function debounceHook(watchFn, wait){
const state = ref(watchFn())
const { run:setState } = debounceFnHook(data => state.value = data, wait)
watch(watchFn, (val) => setState(val) )
return [ state, setState ]
}