[Vuejs]-Cannot run addEventListener (resize) in VueJS CLI to get screen width

0👍

You cannot use window.document in the created() life-cycle hook because the Vue instance is not mounted in the DOM yet. This can be done in mounted().

0👍

According to the docs https://developer.mozilla.org/en-US/docs/Web/API/Window/resize_event:

However, resize events are only fired on the window object

which means you should call

window.addEventListener('resize', this.detectScreenWidth );

instead of document.

Also, as Nikolay Yankov mentioned you should call addEventListener within mounted() method. The resulting code:

mounted(){
    window.addEventListener('resize', this.detectScreenWidth );
}

Leave a comment