vue3 hook

作者: 小北呀_ | 来源:发表于2021-07-12 14:39 被阅读0次

经典的 hook 例子,窗口尺寸发生改变,与其他功能代码无关,可以抽为单独的 hook 。

js文件
import { onMounted, onUnmounted, ref } from "vue";

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

  function 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;
文件使用
<template>
    <div>
        <h1>屏幕尺寸:</h1>
        <div>宽度:{{ width }}</div>
        <div>高度:{{ height }}</div>
    </div>
</template>
<script setup>
import { ref, watch } from "vue";
import useWindowResize from "@/hooks/useWindowResize";
const { width, height } = useWindowResize();
</script>

相关文章

网友评论

      本文标题:vue3 hook

      本文链接:https://www.haomeiwen.com/subject/frdxyltx.html