본문으로 바로가기

728x90

본 포스트에서는 웹브라우저 크기조절에 따른 이벤트를 처리하는 방법에 대해서 설명합니다.

 

필자는 화면의 폭에 따라서 사용자화면을 다르게 보여주기 위해서 리사이즈 이벤트를 처리할 필요가 생겼습니다. 화면의 폭에 따라서 특정한 div의 크기를 자동으로 조절해야 했습니다.

 

vue에서는 자체적으로 window의 resize이벤트 처리가 안되는 관계로 웹브라우저의 window의 이벤트를 등록/제거하는 로직을 추가하고 발생하는 window이벤트를 vue에 전달하여 resize이벤트를 구현하였습니니다.

 

다음은 간단하게 구현된 resize 처리방법입니다.

Vue의 mounted 이벤트시에 window의 resize이벤트를 등록하고 beforeDestory 이벤트 시에는 window의 resize이벤트를 등록해제하는 코드를 삽입합니다. 크기조정 이벤트는 methods에 구현합니다.

<template>
    <div>
        {{ width }}, {{ height }}
    </div>
</template>

<script>
export default {
    data() {
        return {
            width: 0,
            height: 0
        }
    },
    mounted() {
        // console.log("ready...");
        window.addEventListener('resize', this.handleResize);
	},
    beforeDestroy() {
        // console.log("beforeDestroy...");
        window.removeEventListener('resize', this.handleResize);
    },
    methods: {
        handleResize(event) {
            this.width = window.innerWidth;
            this.height = window.innerHeight;
        }
    }
}
</script>

 

관련자료

Add support for a v-on:resize event

https://github.com/vuejs/vue/issues/1915

 

Add support for a v-on:resize event · Issue #1915 · vuejs/vue

It would be nice if there was a built in way to handle resizing. Ex:

 

 

github.com

 

How to trigger an event when element is resized in Vue.js?

https://stackoverflow.com/questions/43813731/how-to-trigger-an-event-when-element-is-resized-in-vue-js

 

How to trigger an event when element is resized in Vue.js?

Currently I trigger an event to take the same height of the current element when the component is mounted, however this doesn't always work since it is sent once and if the element is resized it wo...

stackoverflow.com

 

728x90