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?
@vueuseis one of the best composable libraries out there and has a function for event listeners too, I suggest you to take a look at that vueuse.org/core/useeventlistener/#usage-example