Vuejs 2 - Event Listener
Windows resize event listener
by KomathiKarunakaran
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
<div id="app">
<h1>{{ msg }}</h1> Window width: {{ windowWidth }}
<br> Window height: {{ windowHeight }}
</div>
JavaScript
var app = new Vue({
el: '#app',
data: function() {
return {
msg: 'Hello World! This is a Event listener test.',
windowWidth: 0,
windowHeight: 0,
}
},
mounted() {
this.$nextTick(function() {
window.addEventListener('resize', this.getWindowWidth);
window.addEventListener('resize', this.getWindowHeight);
//Init
this.getWindowWidth()
this.getWindowHeight()
})
},
methods: {
getWindowWidth(event) {
this.windowWidth = document.documentElement.clientWidth;
},
getWindowHeight(event) {
this.windowHeight = document.documentElement.clientHeight;
}
},
beforeDestroy() {
window.removeEventListener('resize', this.getWindowWidth);
window.removeEventListener('resize', this.getWindowHeight);
}
});