经典的 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>
网友评论