Is there a way to track dynamic changes in window dimensions within Vue?

Working on my Vue mobile web app, I encountered an issue with hiding the footer when the soft keyboard appears. I've created a function to determine the window height-to-width ratio...

showFooter(){
    return h / w > 1.2 || h > 560;
}

...and I've set window.innerHeight/window.innerWidth in my data.

data: { h: window.innerHeight, w: window.innerWidth }

The problem arises when window.innerHeight updates, as my 'h' property doesn't reflect the new value. How can I monitor changes in window.innerHeight?

Answer №1

For monitoring the current height of your browser window as it changes, you can utilize the following script:

new Vue({
  el: '#app',
  data() {
    return {
      windowHeight: window.innerHeight
    }
  },

  mounted() {
    this.$nextTick(() => {
      window.addEventListener('resize', this.onResize);
    })
  },

  beforeDestroy() { 
    window.removeEventListener('resize', this.onResize); 
  },

  methods: {  
    onResize() {
      this.windowHeight = window.innerHeight
    }
  }
});

To show this information, insert the following code:

<div id="app">
 Current window height: {{ windowHeight }}
</div>

Answer №2

VUE 2.7 and newer versions

For Vue versions 2.7 and above, a composable has been introduced that allows you to easily create a reactive width and breakpoint name.

import { computed, onMounted, onUnmounted, ref } from "vue"

export const useBreakpoints = () => {
  let windowWidth = ref(window.innerWidth)

  const onWidthChange = () => windowWidth.value = window.innerWidth
  onMounted(() => window.addEventListener('resize', onWidthChange))
  onUnmounted(() => window.removeEventListener('resize', onWidthChange))
  
  const type = computed(() => {
    if (windowWidth.value < 550) return 'xs'
    if (windowWidth.value >= 550 && windowWidth.value < 1200) return 'md'
    else return 'lg' // Triggers when windowWidth.value >= 1200
  })

  const width = computed(() => windowWidth.value)

  return { width, type }
}

You can integrate this in the setup method of your components.

const { width, type } = useBreakpoints()

Note: For simplicity and optimum performance, it is recommended to compute these values only once. To achieve this, implement them within effect scopes so that events are added/removed only within that scope. Alternatively, libraries like vueuse may handle this automatically for you.

Otherwise, initialize this logic close to the entry point, such as App.vue, and manage it through your global state management system or import the composable from a library rather than using provide/inject.

Answer №3

The solution provided didn't resolve my issue. However, the following code snippet did the trick:

mounted() {
  window.addEventListener('resize', () => {
    this.windowHeight = window.innerHeight
  })
}

Answer №4

If you are currently utilizing Vuetify, simply monitor this.$vuetify.breakpoint.width or this.$vuetify.breakpoint.height to detect any alterations in the viewport's size.

Explore Vuetify breakpoint documentation

Answer №5

If you're looking for a simpler solution, consider using npm to install the package vue-window-size and importing it with

import windowWidth from 'vue-window-size';

Alternatively, you can achieve this with the composition API:

setup() {
    const windowSize = ref(window.innerWidth)
    onMounted(() => {
        window.addEventListener('resize', () => {windowSize.value = window.innerWidth} )
    })
    onUnmounted(() => {
        window.removeEventListener('resize', () => {windowSize.value = window.innerWidth})
    })
    return { 
        windowSize
    }
}

Answer №6

While it may be a bit delayed, I wanted to share what I discovered on this particular topic! :)

https://codepen.io/sethdavis512/pen/EvNKWw

HTML :

<div id="app">
    <section class="section has-text-centered">
        <h1 class="title is-1">
            Your Window
        </h1>
        <h3 class="title is-3">
            Width: {{ window.width }} px<br/>
            Height: {{ window.height }} px
        </h3>
        <p class="has-text-white">
            &uarr;<br/>
            &larr; resize window &rarr;<br/>
            &darr;
        </p>
    </section>
</div>

CSS:

$top-color: yellow;
$bottom-color: tomato;

html, body, #app, section.section {
  height: 100%;
}

body {
    background: -webkit-linear-gradient($top-color, $bottom-color);
    background: -o-linear-gradient($top-color, $bottom-color);
    background: -moz-linear-gradient($top-color, $bottom-color);
    background: linear-gradient($top-color, $bottom-color);
}

section.section {
  display: flex;
  flex-flow: column;
  justify-content: center;
  align-items: center;
}

.title {
    color: white;
}

JS:

new Vue({
    el: '#app',
    data: {
        window: {
            width: 0,
            height: 0
        }
    },
    created() {
        window.addEventListener('resize', this.handleResize);
        this.handleResize();
    },
    destroyed() {
        window.removeEventListener('resize', this.handleResize);
    },
    methods: {
        handleResize() {
            this.window.width = window.innerWidth;
            this.window.height = window.innerHeight;
        }
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can we invoke a function through Ajax?

Apologies for my lack of experience, I am just getting acquainted with Ajax. Please bear with me if my question seems unrefined. I attempted to do something, but unfortunately, I did not achieve success. Let me explain what I was trying to accomplish: I ...

What is the best way to incorporate an array of elements into Firebase?

How can I store data from an array to Firebase in a simple manner? Let's say I have an array of elements. function Something() { var elements=new Array() elements[0]=10; elements[1]=20; elements[2]=30; database = firebase.databas ...

Leveraging a JSON file as a data repository for chart.js

I am struggling to incorporate JSON values into a bar chart. I have successfully logged the JSON data in the console, but I'm unsure how to include it in the data property for the chart. Below is the source JSON... {time: "2016-07-03T21:29:57.987Z" ...

ES6 does not work with React hello world

Can anyone help me with troubleshooting my code? I've checked the console on jsbin and can't find any errors. http://jsbin.com/susumidode/edit?js,console,output Class secondComponenent extends React.Component { render(){ return ( &l ...

Utilize jQuery to dynamically assign classes to list items within a unordered list based on the length of an array

HTML: <ul class="tickboxes"> <li><i class="fa fa-check"></i></li> <li><i class="fa fa-check"></i></li> <li><i class="fa fa-check"></i>< ...

DataGrid React MUI: Aligning Column Data and Header for "Number" Type

In my React project, I am using MUI. I noticed that when I specify the type of a column as type: "number", both the column header and data align to the right. This issue can be replicated in a simple example taken from the MUI documentation: code ...

Issue: Exceeding rendering limit. React has a restriction on the number of renders to avoid endless loops

I'm in the process of creating a basic to do list using React, and I've encountered an issue with the handleSubmit() function that I can't seem to resolve. import React, { useState } from "react"; function TaskList() { const [ta ...

Automatically numbering table columns with custom language localization in JavaScript using Jquery

Is there a method to automatically number table data in a local or custom language? As a Bengali individual, I have figured out how to automatically number the first data of each row using css and js. However, I am uncertain about how to implement custom n ...

Error in NodeJs: ReferenceError - the variable I created is not defined

Encountering an issue while attempting to use a module in my router file. I have successfully required it, but now I am seeing the following error message: ReferenceError: USERS is not defined at c:\work\nodejs\router\main.js:32 ...

Conceal any elements that have a class containing specific text

In my HTML file, I have multiple <span> elements with the class of temp_val that include a 1 value which I need to hide. These elements are placed throughout the document. Below is an excerpt from my HTML code: <div class="row" style="float: lef ...

The functions getFiles and getFolders will consistently retrieve a single file or folder each time they are

When attempting to fetch all files and folders from my Google Drive, the function .getFiles() is only returning one file, while .getFolders() is only returning a single folder. However, I can confirm that there are multiple folders and files in my drive. ...

Troubiling Responsive Menu in React

I am currently working on developing a React Responsive Navigation with SCSS, but I am facing an issue. When I click on the hamburger button, nothing happens and the menu does not slide down in the mobile view. I tried inspecting the code in the browser to ...

Tips for creating a responsive fixed div/nav that adjusts its size based on the container it is placed within

Just starting out in web development and struggling with this issue. Any assistance would be much appreciated! When resizing the window, the fixed div moves outside of its container instead of resizing. The navigation bar on the website I'm working o ...

Data assigned to KendoUI chart must have keys that do not consist of numbers

When I input the following simple data into a KendoUI chart, the chart displays the data correctly. var data = [ {"state":"NY","abc":12312}, {"state":"AZ","abc":12312}, {"state":"CA","abc":12312}, ...

Jest tutorial: mocking constructor in a sub third-party attribute

Our express application uses a third-party module called winston for logging purposes. const express = require('express'); const app = express(); const { createLogger, transports } = require('winston'); const port = process.env.PORT | ...

Using Angular Ionic for a click event that is triggered by a specific class

I am utilizing Highcharts and would like to click on the legend upon loading. With the use of Angular Ionic, how can I trigger a click on the .highcharts-legend-item class within the ngOnInit() {} method? I am aiming to click on this class as soon as the ...

Transmitting data from Javascript/Ajax to a form

I am using jQuery to calculate a price: $('.label_1').click(function(){ var total = 0; $('.option_1:checked').each(function(){ total += parseInt($(this).val()); }); $('#total').html(' ...

applying the "active" class to both the parent and child elements

Looking for a way to apply an active class to both the parent and child elements when a user clicks on the child element within a list. The HTML structure is as shown below:- <ul class="tabs"> <li class="accordion"><a href="#tab1"> ...

Using Vue router within a subfolder setup in Laravel framework

I have a Laravel web app running on example.com, and I recently added a new Vue app by placing it in /public/wt with Vue router history mode. I can access the Vue application at example.com/wt, and if not logged in, I get redirected to example.com/wt/login ...

The Jquery ajax call encountered an error due to a SyntaxError when trying to parse the JSON data, specifically finding an unexpected character at

I've developed a web application that utilizes just four scripts for dynamic functionality. Overview: Init.php = Database, index.php = webpage, api.php = fetches data from server/posts data to server, drive.js = retrieves information from api.php a ...