From 4fa602bc77dc8e09c32d44258d8539691a69f078 Mon Sep 17 00:00:00 2001 From: chenjiahan Date: Mon, 14 Sep 2020 17:48:14 +0800 Subject: [PATCH] feat(use): add useWindowSize --- packages/vant-use/src/index.ts | 1 + packages/vant-use/src/useWindowSize/index.ts | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 packages/vant-use/src/useWindowSize/index.ts diff --git a/packages/vant-use/src/index.ts b/packages/vant-use/src/index.ts index dd687cca0..e43f9f31c 100644 --- a/packages/vant-use/src/index.ts +++ b/packages/vant-use/src/index.ts @@ -1,4 +1,5 @@ export { useToggle } from './useToggle'; export { useClickAway } from './useClickAway'; +export { useWindowSize } from './useWindowSize'; export { useScrollParent } from './useScrollParent'; export { useEventListener } from './useEventListener'; diff --git a/packages/vant-use/src/useWindowSize/index.ts b/packages/vant-use/src/useWindowSize/index.ts new file mode 100644 index 000000000..ddaefce73 --- /dev/null +++ b/packages/vant-use/src/useWindowSize/index.ts @@ -0,0 +1,18 @@ +import { ref } from 'vue'; +import { inBrowser } from '../shared'; +import { useEventListener } from '../useEventListener'; + +export function useWindowSize(initialWidth = 0, initialHeight = 0) { + const width = ref(inBrowser ? window.innerWidth : initialWidth); + const height = ref(inBrowser ? window.innerHeight : initialHeight); + + const onResize = () => { + width.value = window.innerWidth; + height.value = window.innerHeight; + }; + + useEventListener('resize', onResize); + useEventListener('orientationchange', onResize); + + return { width, height }; +}