-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathuseResize.ts
30 lines (27 loc) · 856 Bytes
/
useResize.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import { DeepReadonly, readonly, Ref, ref } from 'vue'
import { useEvent } from './useEvent'
import { useDebounceFn } from './useDebounceFn'
export interface ResizeHandler {
(this: Window, e: WindowEventMap['resize']): any
}
export interface IResizeState {
width: DeepReadonly<Ref<number>>
height: DeepReadonly<Ref<number>>
}
export function useResize(handler: ResizeHandler | null = null, delay = 200): IResizeState {
const width = ref(window.innerWidth)
const height = ref(window.innerHeight)
let cb: ResizeHandler = function (this: Window, e: WindowEventMap['resize']) {
handler && handler.call(this, e)
width.value = window.innerWidth
height.value = window.innerHeight
}
if (delay) {
cb = useDebounceFn(cb, delay)
}
useEvent('resize', cb)
return {
width: readonly(width),
height: readonly(height)
}
}