vue3 创建hooks监听屏幕宽高

2023-02-03

创建hooks/useWindowResize.ts


const useWindowResize = () => {
  const width = ref(0);
  const height = ref(0);

  const onResize = () => {
    width.value = window.innerWidth;
    height.value = window.innerHeight;
  };

  onMounted(() => {
    window.addEventListener("resize", onResize);
    onResize();
  });

  onUnmounted(() => {
    window.removeEventListener("resize", onResize);
  });

  return {
    width,
    height,
  };
};

export default useWindowResize;

 

使用(index.vue):

<script setup lang="ts">

const { width, height } = useWindowResize();

</script>