Reputation: 109
I'm relatively new to vue. In react, I can use useEffect in my custom hooks, but I don't have any idea how to do it in vue. I wanted to create a custom hook for listening window resize, Here's how I did it in react.
useDimension.js
import React, { useState, useEffect } from 'react';
function getWindowDimensions() {
const { innerWidth: width, innerHeight: height } = window;
return {
width, height
};
}
export default function useWindowDimensions() {
const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());
useEffect(() => {
function handleResize() {
setWindowDimensions(getWindowDimensions());
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, [])
return windowDimensions;
}
and I call it in my component like let {width, height} = useDimensions()
How do I do it on vue3? compositionAPI?
Upvotes: 0
Views: 2003
Reputation: 1656
//useDimension.js hook
import { ref, onMounted, onUnmounted } from 'vue';
const useDimension=()=> {
const width = ref(window.innerWidth);
const height = ref(window.innerHeight);
const handleResize = () => {
width.value = window.innerWidth;
height.value = window.innerHeight;
}
onMounted(()=> window.addEventListener('resize', handleResize))
onUnmounted(()=> window.removeEventListener('resize', handleResize))
return {width,height}
};
export default useDimension;
then you can use it in the App.vue like
<script setup>
import useDimension from './useDimension.js'
const {width,height} = useDimension()
</script>
<template>
<h1>({{width }},{{ height}})</h1>
</template>
Upvotes: 3