0

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?

2

1 Answer 1

3
 //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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.