useWindowSize.ts 583 B

12345678910111213141516171819202122232425
  1. import {
  2. Ref,
  3. onMounted,
  4. onUnmounted,
  5. reactive,
  6. toRefs,
  7. } from "@nuxtjs/composition-api"
  8. interface WindowSize {
  9. x: Ref<number>
  10. y: Ref<number>
  11. }
  12. export function useWindowSize(): WindowSize {
  13. const windowSize = reactive({ x: 0, y: 0 })
  14. const resizeListener = () => {
  15. ;({ innerWidth: windowSize.x, innerHeight: windowSize.y } = window)
  16. }
  17. onMounted(() => window.addEventListener("resize", resizeListener))
  18. onUnmounted(() => window.removeEventListener("resize", resizeListener))
  19. resizeListener()
  20. return toRefs(windowSize)
  21. }
  22. export default useWindowSize