Creating a VueJS computed property that dynamically responds to changes in the `window.innerWidth`

Essentially, I am searching for a computed property that will evaluate to true when the window.innerwidth is 768px or less and to false when it exceeds 768px.

This is what I have attempted:

computed: {
  isMobile() {
    if (window.innerWidth <= 768) {
      return true
    } 
    return false
  }
}

However, this computes the property only once, so any changes in window size are not reflected. How can I address this issue?

Answer №1

To ensure responsiveness, you can add an event listener to the window in your Vue component:

new Vue({
  el: "#app",
  data() { return { windowWidth: window.innerWidth } },
  mounted() {
    window.addEventListener('resize', () => {
      this.windowWidth = window.innerWidth
      console.log(this.isMobile)
    })
  },
  computed: {
    isMobile() {
      return this.windowWidth <= 768
    }
  }
})

Answer №3

For computed properties to update, they rely on changes in their dependencies. This means that the isMobile property may not be reactive.

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

Tips for presenting validation messages from the server on the client side using react-query

Hey there! I have set up the Express route for the signup API call, which is functioning correctly on the server-side. However, my goal is to show these validation messages in real-time as the user inputs their credentials on the React client side app.post ...

Finding a problem in node.js

I have encountered a problem while creating a server game using node.js. I am seeking assistance to resolve this issue. Here is the specific problem: https://i.stack.imgur.com/FMlsL.png app.js: var express = require('express'); var app = expr ...

How to retrieve the total count of fields in AngularJS

Could you please specify the number of choices you would like to display? For example, if the user enters 10, then 10 choices will be displayed. I have been trying to implement this functionality, but it keeps resulting in a memory error. dynamicform.jsp ...

Is there a way to show several elements simultaneously by hovering over another?

Can anyone help me with setting display:block; on all the p tags and the overlay div when I hover over my img tag? Is this achievable with just CSS or do I need to incorporate some JavaScript? Open to suggestions on the best approach. Any assistance woul ...

The icon displays correctly in Firefox but is not visible in IE

link REL="SHORTCUT ICON" HREF="/images/greenTheme/favicon.ico" type="image/x-icon" While this code functions properly in Firefox, it appears to be causing issues in Internet Explorer. Can anyone provide guidance on how to resolve the compatibility issue w ...

If a span element is present, apply a specific class to the corresponding

I am working with a dynamic list of links retrieved through AJAX. After parsing the links and appending them to a div, I have encountered an issue where some 'a' elements are followed by a 'span' that needs to be considered. Here is th ...

AngularJS - Issues with Firebase resetPassword not showing updated changes

When incorrect email addresses are entered and the form is submitted, the error message does not display for the user. However, if additional characters are appended to the existing entries, the message appears on the screen. In debugging, the variable $sc ...

"Using JavaScript to initiate a popup window that displays a specific destination link

Whenever I view this code, the iframe popup automatically opens. But I want the iframe to open only when I click the "click me" button. Can someone please assist me with this? I believe it's a simple trick, but as a JavaScript amateur, I am struggling ...

Shade the entire td column in different colors depending on the characteristics of th

I am working with a table and here is the code for it: <table> <thead> <tr> <th style="width: 40%; text-align: center; vertical-align: center;">Nr.<br> crt.</th> <th style="font-weight: bold; wi ...

Step-by-step guide on writing to a JSON file using Node.js

I am currently developing a Facial Recognition web application using React for the frontend and Node.js for the backend. You can find more information about my project here. So far, I have completed the frontend part where users manually add 128-d descript ...

Switch the cursor to display the magnifying glass icon for zooming in and out

I am curious about how to modify the cursor shape to display a zoom in and zoom out symbol. Changing the cursor to indicate busy or wait status is something I am familiar with, document.manual_production.style.cursor='wait'; However, I am unsu ...

What is the best way to convert Arabic language HTML into a PDF document on the client side?

Utilizing jsPDF and vue js, I successfully implemented a feature to export PDFs. However, I encountered an issue with Arabic characters not displaying properly. Can anyone provide assistance in resolving this problem? ...

What methods can be utilized to enhance the visual appeal of a threejs model

I'm currently working on enhancing the visual quality of my 3D models, aiming for smoother edges and more realistic shadows. To achieve this, I am experimenting with an OBJ file format. Here's the code snippet I'm using to load and display t ...

"An issue with the setTimeout function in React is leading to the page constantly refreshing

My buddies and I are in the process of developing a React App. The main goal is to identify the currently logged-in user, then send a post request to fetch everyone in the same "room" as them and display this information on the app upon page load. However, ...

Turning an Array of Objects into a typical JavaScript Object

Below are arrays of numbers: var stats = [ [0, 200,400], [100, 300,900],[220, 400,1000],[300, 500,1500],[400, 800,1700],[600, 1200,1800],[800, 1600,3000] ]; I am seeking guidance on how to transform it into the JavaScript object format shown below. ...

What is the best way to utilize Typescript when making queries to Firebase?

I have successfully integrated push notifications for my app using Firebase Cloud Functions. Now, I am looking to enhance the user experience by updating the app's badge count alongside the push notifications. I understand that this can only be achiev ...

Steps for invoking a function in an HTML document from an external jQuery script

Can you please assist me with the logic and approach to execute a function in an HTML document after a function in an external jQuery file has been executed? I have two separate jQuery files. One is responsible for creating tables, while the other, timesh ...

`Utilizing lightgallery.js in combination with Vue 3: A comprehensive guide`

I'm encountering a 500 [vite-node] [ERR_MODULE_NOT_FOUND] error related to 'lightgallery/vue' module. Can anyone provide guidance on resolving this issue? I am currently working with Nuxt version v3.0.0-rc.12 and Vue version v3.2.41 <scr ...

Setting up isotope using dynamic JSON data

I've done some searching, but without any luck. My current dilemma involves utilizing the isotope jQuery library to display data in a dynamic manner using a JSON dataset. I've stored the data in a .json file and am reading it in, parsing the info ...

Ensuring File Arrival in JavaScript and Handling HttpResponse Object in Django

I've got my code running smoothly, but I'm stuck on how to detect when a file arrives in JavaScript. Currently, I'm working with Django 2.1. This is a snippet of the template: ... <form method="POST" enctype="multipart/f ...