In Vue JS, assign a boolean value to a variable based on the screen width

Currently, I am working on a responsive navigation menu. I have completed the mobile view, but now I face an issue for the desktop view. I want to hide the button that toggles the mobile navbar and only display the navbar. However, the navbar is linked to a reactive variable using the "v-if" directive. How can I display the navbar in this scenario? I considered setting the variable true or false based on the screen size, but I cannot create a method due to the click event that also changes the variable value to toggle the menu on mobile screens. What would be the best approach to tackle this? Is there any way to remove the "v-if" on larger screens? Thank you for your assistance.

//reactive variable==========================
const showUserDropdown = ref(false)

//=================mobile toggle button=====================
<div class="pt-1 text-right">
    <button class="text-right md:hidden" @click="showDropdown = !showDropdown">
         <Icon :name="showDropdown ? 'up' : 'menu'" class="w-6 h-6 inline-block fill-cyan-800" />
    </button>
</div>
//====================mobile nav==================
nav class="" v-if="showDropdown">
   <ul class="">
       <li v-for="(item, index) in menu" :key="item.id" class="pb-2">
             <Link>
                 <Icon :name="item.icon_name" class="w-5 h-5 mr-2 inline fill-slate-500" />
                 <span class="capitalize"> {{ item.name }}</span>
             </Link>
       </li>
    </ul>
</nav>

Mobile View: ========================

Desktop View: =============================

Answer №1

A more efficient way to update a variable based on screen width changes is by using matchMedia instead of constantly triggering a resize event.

<script setup>
const isMobile = ref('')
let mql

function handleMqlChange(e) {
  isMobile.value = e.matches
}

onMounted(() => {
  mql = window.matchMedia('(max-width: 1024px)')
  isMobile.value = mql.matches
  mql.addEventListener('change', handleMqlChange)
})

onUnmounted(() => {
  mql.removeEventListener('change', handleMqlChange)
})
</script>

To utilize this method, simply use v-if="isMobile". This will accurately reflect changes in screen size upon page load, as well as adjustments made by the user such as device orientation change or browser tab resizing.

Answer №2

The global window object contains valuable information about screen width. See below for a breakdown of the properties available in the window.screen object.

Screen {
  availHeight
  availLeft
  availTop
  availWidth
  colorDepth
  height
  isExtended
  onchange
  orientation: ScreenOrientation {
    angle
    onchange
    type
    [[Prototype]]: ScreenOrientation
  }
  pixelDepth
  width
  [[Prototype]]: Screen
}

To access the screen width dynamically, you can create reactive properties using window.screen.width or window.screen.availWidth, depending on your specific requirements.

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

Querying MongoDB with a JavaScript file for formatting datetime values

I am utilizing mongodb3.0.5 and my database collection appears as follows: { "_id" : "xxxxxxxxxxxxxxx", "SchoolId" : 1, "ActivationTimestamp" : ISODate("2015-09-22T13:01:58.000Z"), "PersonDetails" : [ { "Name" : "John" ...

The quickForm Meteor encountered an exception in the template helper: There was an error stating that Recipes is not within the window

I'm having trouble getting the app to work on Meteor. The quickform is not connecting to my Collection. "Error: Recipes is not in the window scope" Can anyone offer assistance with this issue? Below is my quickform code: <template name="NewRe ...

Using React Router useHistory to navigate to different routes programmatically

Currently, I'm working on creating a wizard interface and running into some issues with the buttons. Right now, I have next and back buttons for each route, but I am aiming to create a button component that can handle navigation both forward and backw ...

Updating global variable in JavaScript at inappropriate times

Within this code: window.g_b_editEnable = false; window.g_a_PreEditData = 'hello'; function EditRow(EditButton){ if(!window.g_b_editEnable){ window.g_b_editEnable = true; var a_i_Pos = a_o_table.fnGetPo ...

While JSON Lint may declare the JSON data as valid, JSON.parse may still encounter an error when trying

I'm struggling to parse a simple JSON object. It's strange because when I check the validity of my JSON string on JSONLint (http://jsonlint.com/), it shows that it's valid. var data = '{"token":"9eebcdc435686459c0e0faac854997f3","email ...

The Puppeteer software does not automatically shut down the browser once the task is complete

Currently, I have set up puppeteer on my Ubuntu server with Express and Node.js like so: var puppeteer = require('puppeteer'); var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/&ap ...

Linking Data to Asp.net HighCharts through Jquery Json

I currently have an asp.net chart that displays monthly attendance data. The chart includes a dropdown menu where users can select the desired month and click a button. Upon clicking the button, I need to call an ActionResult method that retrieves data fr ...

Tips on maintaining the parent's scope in CoffeeScript while making an AJAX call

I need to iterate through an object in CoffeeScript and make an AJAX call for each item in the object using jQuery. However, I'm facing an issue with losing the reference to the initial context in the callback function of the AJAX call. The context al ...

Utilize JavaScript to send login information to a website

I have a specific task in mind: creating a script that will automatically fill in certain data on an HTML website. To illustrate, let's imagine the site is the StackOverflow login page and I want to input my username and password. For the username fi ...

Learn how to use React.js props in your index.html file to

Issue: Unable to locate React props I am currently facing difficulties in accessing React props on the index.html page. This is the main page where I need to render meta tags properties that are fetched from the backend. I need to access my store data on ...

I am exploring directories on my server but encountered a restriction while using $.ajax

I am currently working on designing a basic webpage using p5.js, where I have implemented a script to search for images within folders and display them all on a single page. To facilitate this process, I am utilizing the $.ajax({}); function to check ...

Using trackBy in conjunction with the async pipe

Attempting to utilize the async pipe along with *ngFor to exhibit an array of items obtained asynchronously. <ul> <li *ngFor="let item of items | async; trackBy: trackPost"> {{item.text}} </li> </ul> ngOnInit() { // a si ...

Can anyone provide me with an explanation of the purpose of the "ref()" function?

I'm confused about why the "ref()" function is necessary when creating a state... The VueJS documentation provides an example like this: import { ref } from 'vue' // global state, created in module scope const globalCount = ref(1) export f ...

The active class in the Bootstrap carousel is not updating when trying to change

I am struggling to make the Twitter Bootstrap carousel function properly. Although the slides automatically change after the default timeout, the indicators do not switch the active class, resulting in my carousel failing to transition between slides. Ini ...

The Slider component in Material UI's API may not properly render when using decimal numbers as steps or marks in React

I am having trouble creating a Material UI slider in my React application. I can't figure out which property is missing. Below is the code for my React component: import * as React from 'react'; import Slider from '@material-ui/core/S ...

After deploying, Vuetify elements look misaligned on the Netlify website

Our team recently completed the development of a website using VueJS. We utilized Vuetify elements like vue-extension-panels and v-card on one of the pages. While in the development phase running npm run dev, everything seemed to be working perfectly. All ...

@keyframes shimmering-fade

I'm attempting to create a text animation effect (please see video) but I'm struggling to find the solution!! Can someone assist me with this? Should I use JavaScript for a better result? h1.fadeinone { animation: fadeinone 10s;} h1.fadeintwo ...

Tips for retrieving user input from an HTML form and using it to make an Axios POST request

I am facing an issue with sending a post request to my API using axios. A user enters an email and password in a html form, but when the request is sent, the body of the request appears to be empty based on the chrome dev tools. I am struggling to extract ...

What are the reasons for validation failure when it is moved into a method?

I am currently in the process of developing a validation function in JavaScript. However, when I extracted the logic into a private method, my validation started failing and I can't seem to figure out why. Here is my HTML definition: <input type= ...

Creating an Online Photo Album with JavaScript

Looking for assistance to finish up my photo gallery project. I have created thumbnails that display 5 images at the top of my page, and below them is a div that should show the selected image in its original size when clicked. Can anyone guide me on what ...