mya-ake / vue-window-size

Provides reactivity window size properties for Vue.js
https://www.npmjs.com/package/vue-window-size
MIT License
122 stars 5 forks source link

Vue warning in console when using outside of a component #423

Closed maxnankivell closed 2 years ago

maxnankivell commented 2 years ago

I'm getting this warning when using useWindowSize() outside of a component with Vue 3 and the composition API vue-warning

I have a typescript file with a computed property in it which I want to re-use in multiple components (code below)

import { computed } from "vue";
import { useWindowSize } from "vue-window-size";

const { width } = useWindowSize();
export const useImageSize = computed(() => {
  if (width.value < 1460) {
    return `125px`;
  }
  return `175px`;
});

Wondering if I'm using the library wrong or if this is something that could be avoided with a change.

mya-ake commented 2 years ago

@maxnankivell Since useWindowSize uses the Composition API(Lifecycle Hooks) internally, it must be called in the component. Therefore, if you want to make a common function, define it as a function and call the function in the component. I think useImageSize may be defined as follows.

export const useImageSize = () => {
  const { width } = useWindowSize();
  return computed(() => {
    if (width.value < 1460) {
      return `125px`;
    }
    return `175px`;
  };
};
maxnankivell commented 2 years ago

Hey @mya-ake Thanks for the fix that makes sense