0

I'm trying to hide a button text when a page width is less than 420px.
To achieve my goal I created a composable that continuosly checks page width and updates a reactive variable pageWidth_. The composable exports a computed property pageWidth to be used in the template, e.g. v-if="pageWidth(420)".

There are no problems with this code an a classic vue app, but with nuxt there must be another approach since it's using SSR. How would you fix the issue?

<template>
  <div id="the-header">
    <BaseButton>
      <template #left>
        <BaseIcon icon="menu" class="padding-small" />
      </template>
      <span v-if="pageWidth(420)">Menu</span>
    </BaseButton>
  </div>
</template>

Composable (usePageSize.ts)

import { ref, computed } from 'vue'

const getPageWidth = function () {
  if (typeof window !== 'undefined') {
    return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
  } else {
    return 0;
  }
}

const pageWidth_ = ref<number>(getPageWidth());

const tickPageWidthUpdateInterval = (function () {
  let pageWidthUpdateTimeout: ReturnType<typeof setTimeout>
  return () => {
    clearTimeout(pageWidthUpdateTimeout)
    pageWidthUpdateTimeout = setTimeout(function () {
      pageWidth_.value = getPageWidth()
    }, 100)
  }
})();

if (typeof window !== 'undefined') {
  window.addEventListener('resize', function () {
    tickPageWidthUpdateInterval()
  })
}

const pageWidth = computed(() => {
  return function (width: number | string) {
    return pageWidth_.value > Number(width)
  }
})

const usePageSize = () => {
  return { pageWidth }
};

export { usePageSize }
manidos
  • 3,244
  • 4
  • 29
  • 65

1 Answers1

0

Fixed by adding tickPageWidthUpdateInterval. Not perfect, but works.

const usePageSize = () => {
  tickPageWidthUpdateInterval();
  return { pageWidth }
};
manidos
  • 3,244
  • 4
  • 29
  • 65