From 2008982ff96d88dbca931a12b17aa6a8c09275a2 Mon Sep 17 00:00:00 2001 From: neverland Date: Mon, 11 Oct 2021 20:47:29 +0800 Subject: [PATCH] perf(@vant/use): reduce event listener of useWindowSize (#9658) * perf(@vant/use): reduce event listener of useWindowSize * chore: update --- packages/vant-use/src/useWindowSize/index.ts | 26 +++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/packages/vant-use/src/useWindowSize/index.ts b/packages/vant-use/src/useWindowSize/index.ts index 6a9c90662..02230d56c 100644 --- a/packages/vant-use/src/useWindowSize/index.ts +++ b/packages/vant-use/src/useWindowSize/index.ts @@ -1,18 +1,26 @@ -import { ref } from 'vue'; +import { ref, Ref } from 'vue'; import { inBrowser } from '../utils'; import { useEventListener } from '../useEventListener'; +let width: Ref; +let height: Ref; + export function useWindowSize() { - const width = ref(inBrowser ? window.innerWidth : 0); - const height = ref(inBrowser ? window.innerHeight : 0); + if (!width) { + width = ref(0); + height = ref(0); - const onResize = () => { - width.value = window.innerWidth; - height.value = window.innerHeight; - }; + const update = () => { + if (inBrowser) { + width.value = window.innerWidth; + height.value = window.innerHeight; + } + }; - useEventListener('resize', onResize); - useEventListener('orientationchange', onResize); + update(); + useEventListener('resize', update); + useEventListener('orientationchange', update); + } return { width, height }; }