Stop access to geojson files through targeted media queries

Using a vue.js app, I have the ability to choose locations using either a map or an input field. However, for mobile users, I want to exclude the map and only serve the search engine.

The issue is that it's not very user-friendly on mobile devices because even though I have prevented the map from displaying with a media query, I am still unable to prevent the downloading of a large geojson file and other related data files.

The imports are structured like this:

//modules for leaflet
import Vue2Leaflet from '../../node_modules/vue2-leaflet/dist/vue2-leaflet.js'; 
import { InfoControl, ReferenceChart, ChoroplethLayer } from 'vue-choropleth'
//geojson and data files
import { geojsonA } from '../../data/mygeojson.min.geojson' 
import { specificData } from '../../data/mydata.js'

and in the styles:

@media (min-width: 640px) {
  .mobile {
    display: none;
  }
  //other styles
}  

Is there a way to selectively block import based on media queries or any other method for specific displays?

Answer №1

In order to make conditions based on the width of the window in Vue, it is necessary to define the media query in JavaScript as well. Since these values are not reactive and cannot be easily watched with Vue, a custom watcher needs to be implemented.

Here is an illustration of how this can be done: The <test/> element will only be displayed if the screen meets certain width criteria. If the screen width does not meet the requirements, the element will not be loaded (v-if removes it from the DOM). A event listener for the resize event of the window is added during the mounted lifecycle hook. This listener updates a value each time the window is resized, which can then be used in a computed property called largeScreen to determine if the screen is considered large or not. This boolean value is used in the template rendering logic. Finally, remember to remove any custom event listeners in the beforeDestroy lifecycle hook to avoid multiple definitions.

Vue.component('test', {
  template: '<div>Large screen; <code>test</code> is loaded.</div>'
});

new Vue({
  el: '#app',
  data: function() {
    return {
      windowWidth: 0
    };
  },
  mounted() {
    this.setWindowWidth();
    window.addEventListener('resize', this.setWindowWidth);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setWindowWidth);
  },
  computed: {
    largeScreen: function() {
      return this.windowWidth > 640;
    }
  },
  methods: {
    setWindowWidth: function() {
      this.windowWidth = window.innerWidth;
    }
  }
});
<script src="https://unpkg.com/vue"></script>

<div id="app">
  Screen width is: <code>{{ windowWidth }}px</code>

  <test v-if="largeScreen" />
</div>

Answer №2

Utilize matchMedia in JavaScript to establish media query breakpoints:

Learn more about matchMedia on MDN

if (window.matchMedia("(min-width: 400px)").matches) {
  /* When the viewport is at least 400 pixels wide */
} else {
  /* When the viewport is less than 400 pixels wide */
}

This method offers excellent support and may be simpler to implement compared to using a resize listener, while also being more efficient in terms of resources.

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

Lock the "tr" element dynamically at the bottom of the table

Is there a way to keep a specific tr at the bottom of a table using VUE or Js? I have a Vue component that dynamically adds table rows based on an API call. However, I need a specific tr to always be at the bottom, and whenever a new tr is added, it shoul ...

Tips for accessing a composition function in VueJS from another composition

I've been diving into the new composition-api within VueJS and have encountered a problem that I need help with. I am seeking advice on how to effectively tackle this issue. Previously, when everything was vuex-based, dispatching an action to another ...

Ways to make a DIV element extend to fill the height of its parent container

Need help with stretching two child DIVs in a Bootstrap 5 page to match the height of the parent DIV. Can anyone assist? Here is the HTML: https://jsfiddle.net/og7pz9sq I'm attempting to make the light-green and light-yellow DIVs fill the entire whi ...

What is the best way to delete spaces between span elements while preserving the spaces within each individual span tag?

Is there a way to eliminate unexpected spaces that appear between spans? One attempt was made by setting font-size: 0 within the wrapper <div>, which successfully removed spaces not only between <span> tags but also within each <span> ta ...

Experience the magic of playing HTML5 video within the sleek confines of an iPhone image

After coming across a similar inquiry on Stack Overflow (), I decided to create my own solution since the original answer lacked code details. The task at hand is to embed an HTML5 video within an iPhone image frame, like so: The image dimensions are 300 ...

What is the best way to design a div that showcases text on top of a background image, complete with a pointer or arrow, and automatically adjusts its width to properly display the

Is it possible to create a div with an :after selector, containing text that automatically adjusts its width to fit the content? Seems like a complex task, right? It sure can be. I initially tried achieving this using a div id and :after selector, but ra ...

Customizing colors in React Material UI

Can colors in Material UI be overridden without the use of JS? Is it possible to override colors using CSS alone? ...

Seamlessly connect Gridsome with HubSpot for advanced page tracking

As a novice developer who has recently taken on clients, I encountered a request to integrate a website with the HubSpot page tracker. After checking the developer page, I realized that there are no specific instructions for Gridsome, which is what my app ...

Unexpected issue encountered for identifiers beginning with a numerical digit

Is it possible to select an element from a page with an id that begins with a number? $('#3|assets_main|ast_module|start-iso-date') Upon attempting to do so, the following error occurs: Uncaught Error: Syntax error, unrecognized expression: ...

Display the hover effect for the current card when the mouse is over it

When the mouse hovers over a card, I want only that specific card to show a hover effect. Currently, when I hover over any card, all of them show the hover effect. Is there a way to achieve this in Vue Nuxtjs? Here's what I am trying to accomplish: ...

vue-authenticate: Can you point me to the location where the $auth variable is defined?

I'm currently working on integrating Vue-authenticate, but I've encountered an issue with the sample code provided in their documentation: new Vue({ methods: { login: function () { this.$auth.login({ email, password }).then(function ...

Aligning a table at the center of another table

Frustration has been brewing within me all week as I grapple with the task of sending out an important emailer soon. The challenge lies in aligning these product images next to their descriptions at the center, a feat that seems impossible to achieve withi ...

SwipeJS is not compatible with a JQuery-Mobile web application

I am currently attempting to integrate SwipeJS (www.swipejs.com) into my JQuery-Mobile website. <script src="bin/js/swipe.js"></script> <style> /* Swipe 2 required styles */ .swipe { overflow: hidden; ...

How do I trigger a click event on an autocomplete search bar in Vue with a router link enabled?

I'm working on an app that is similar to Github, and I want to create a search bar functionality just like Github's. However, I'm facing an issue with my search bar located in the navbar option section as it doesn't seem to register any ...

Unlocking the variables within a v-for loop post-mounted: A guide to accessing and updating them

I have a question regarding my code snippet below. The calculation of Ending Inventory involves adding the beginningInventory, newInventory, and totalSold values. How can I access the value property of endingInventory in order to update it? Any assistance ...

Organizing CSS DIV code by sections for desktops and mobile devices

My CSS file contains properties that are common for both PC and cellphone browsing, but some vary between the two platforms. I utilize @media screen and (max-width: X px) to handle this, with one set of rules for narrow screens and another for wider screen ...

Grid of domes, fluid contained within fixed structures and beyond

I've been grappling with this issue for a while now, and have had to rely on jQuery workarounds. I'm curious if there is a way to achieve this using CSS or LESS (possibly with javascript mixins). The page in question consists of both fixed and f ...

What is the best way to position an image next to an input element?

How can I position submit.png next to the input element in my code? <div class="input-box" style="height: 40px; width: 500px;"> <img src="img/delete.png" width="25px" height="25px;" style="position: absolute; right: 0;"> ...

Tooltip not appearing in designated spot as designed

I seem to be having an issue with the positioning of my custom tooltip on a graph. The arrow mark in the tooltip is not displaying where it should be. Can anyone help me figure out what I'm doing wrong? If you'd like to see exactly what I mean, ...

Using Vue JS to dynamically update checkboxes when a radio button is selected

I have a similar question to someone on Stack Overflow, but I am using Vue JS instead of jQuery. In my scenario, I have N groups linked to an array called ensemble_groups displayed as radio buttons. The selected value is stored in selected_group. Additio ...