Vue Composition API - useWindowSize
by nolleto
HTML
<script src="https://unpkg.com/vue@next"></script>
<body>
<div id="app">
<my-component />
</div>
</body>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
h2 {
margin-bottom: 8px;
}
JavaScript
const { ref, onMounted, onUnmounted, createApp } = Vue
const app = createApp({});
const getWindowWidth = () => window.innerWidth;
const getWindowHeight = () => window.innerHeight;
const useWindowSize = () => {
const width = ref(getWindowWidth());
const height = ref(getWindowHeight());
const onResize = () => {
width.value = getWindowWidth();
height.value = getWindowHeight();
};
onMounted(() => {
window.addEventListener('resize', onResize);
});
onUnmounted(() => {
window.removeEventListener('resize', onResize);
});
return { width, height };
};
app.component('my-component', {
setup() {
const { width: windowWidth, height: windowHeight } = useWindowSize()
return { windowWidth, windowHeight }
},
template: `
<div>
The window size:
<p>Width: {{ windowWidth }}</p>
<p>Height: {{ windowHeight }}</p>
</div>
`
})
app.mount("#app");