Monitoring window size changes in Vue can be implemented in several ways. The most common approach involves utilizing the resize event of the window object and managing event listeners within Vue component lifecycle hooks. I will detail the implementation below.
1. Using Lifecycle Hooks
Within Vue components, add the resize event listener in the mounted hook and remove it in the beforeDestroy hook. This ensures the listener is added only when the component is mounted to the DOM and properly cleaned up before destruction to prevent memory leaks.
Example Code:
javascript<template> <div> <h1>Current window width: {{ windowWidth }}</h1> </div> </template> <script> export default { data() { return { windowWidth: window.innerWidth }; }, methods: { handleResize() { this.windowWidth = window.innerWidth; } }, mounted() { window.addEventListener('resize', this.handleResize); }, beforeDestroy() { window.removeEventListener('resize', this.handleResize); } } </script>
2. Managing State with Event Bus or Vuex
If your application is complex or multiple components need to respond to window size changes, consider using a global event bus or Vuex to manage the window size state. This approach centralizes state management and simplifies maintenance.
Using Event Bus:
Add an event bus to the Vue prototype to trigger and listen for window size change events.
javascript// main.js import Vue from 'vue'; Vue.prototype.$bus = new Vue(); // Add event bus // In component mounted() { window.addEventListener('resize', () => { this.$bus.$emit('window-resize', window.innerWidth); }); }, beforeDestroy() { window.removeEventListener('resize'); } // Another component that depends on window width created() { this.$bus.$on('window-resize', (width) => { console.log('Window width changed:', width); }); }, beforeDestroy() { this.$bus.$off('window-resize'); }
Using Vuex:
Define a window width state in the Vuex store and update it via the resize event of the window.
javascript// store.js export default new Vuex.Store({ state: { windowWidth: window.innerWidth }, mutations: { setWindowWidth(state, width) { state.windowWidth = width; } }, actions: { updateWindowWidth({ commit }) { window.addEventListener('resize', () => { commit('setWindowWidth', window.innerWidth); }); } } });
In components, call this action to initialize the listener and use computed properties to respond to state changes.
These are common methods for monitoring window size changes in Vue. The method you choose depends on your specific requirements and project structure.