Define a custom Vue directive
In this approach, we will define a custom vue directive to monitor changes. The bind hook will be used to attach a window resize event listener. This approach allows you to apply the v-resize directive to any element and customize the behavior in the associated method. We define a custom Vue directive named resize. The directive calls the specified method (handleResize in this case) with the current width and height of the element whenever a resize occurs. The unbind hook removes the event listener when the element is unbound.
Example: The below code example explains the use of the custom vue directive to monitor changes in the window sizes.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content=" width = device -width, initial-scale = 1 .0"> < title > Vue Window Resize Monitor </ title > </ head > < body > < div id = "app" > < div v-resize-window = "handleResize" > < h1 > Vue Window Resize Monitor </ h1 > < p > Window Width: {{ windowWidth }}px </ p > < p > Window Height: {{ windowHeight }}px </ p > </ div > </ div > < script src = "https://cdn.jsdelivr.net/npm/vue@2" > </ script > < script > Vue.directive('resize-window', { bind(el, binding) { const handleResize = () => { binding.value( window.innerWidth, window.innerHeight); }; window.addEventListener ('resize', handleResize); el._handleResize = handleResize; // Call the handler once // to initialize the dimensions handleResize(); }, unbind(el) { window.removeEventListener ('resize', el._handleResize); }, }); new Vue({ el: '#app', data() { return { windowWidth: 0, windowHeight: 0, }; }, methods: { handleResize(width, height) { // Update data properties // with new dimensions this.windowWidth = width; this.windowHeight = height; // Additional logic based on // window size changes console.log( 'Window dimensions changed:', this.windowWidth, this.windowHeight); }, }, }); </ script > </ body > </ html > |
Output:
Conclusion
Monitoring and responding to changing window size in a Vue.js application is essential for creating responsive and dynamic user interfaces. There are several approaches to achieve this, and the choice depends on your specific requirements and preferences.
How to Monitor Changing Window Sizes in VueJS ?
Monitoring changing window sizes in a Vue.js application is crucial for creating responsive designs. Vue provides a few ways to achieve this, allowing you to dynamically respond to changes in the window dimensions. In this article, we will learn How to monitor changing window sizes in Vue.
Two common approaches involve using the window object directly or utilizing the Vue resize event.
Table of Content
- Using window Object Directly
- Define a custom Vue directive