Customizing the style of an element in Vue depending on the size of the window

I am struggling to update the appearance of an HTML element when the window size is below 500px. Currently, I have a computed property that sets a background-image for the element. I attempted to use an if statement within the computed property to check if window.innerWidth < 500, but it appears that logic cannot be used inside computed properties. My most recent effort involved creating a method to check the window width, and if it's less than 500, to update the computed property with the new value. However, this approach doesn't seem to be working.

Any assistance would be greatly appreciated. Thank you!

<template>
  <div class="hero" :style="bgImage">
</template
data() {
    return {
      window: {
        width: 0
      }
    }
  },
  created() {
    window.addEventListener('resize', this.handleResize)
    this.handleResize()
  },
  destroyed() {
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    handleResize() {
      if (window.width < 500) {
        this.bgImage = `backgroundImage: linear-gradient(to bottom,rgba(245, 246, 252, 0) 45%,rgb(0, 0, 0) 100%), url(${this.hero.image})`
      }
    }
  },
  computed: {
    bgImage() {
      return {
        backgroundImage: `url(${this.hero.image})`
      }
    }
  }

Answer №1

Utilize the computed property to monitor changes in your width data.

I have made modifications to your code as follows:

export default {
  data() {
    return {
      window: {
        width: 0,
      },
    },
    computed: {
      bgImage() {
        if (this.width < 500) {
          return {
            backgroundImage: `linear-gradient(to bottom,rgba(245, 246, 252, 0) 45%,rgb(0, 0, 0) 100%), url(${this.hero.image})`
          }
        } else {
          return {
            backgroundImage: `url(${this.hero.image})`
          }
        }
      }
    }

    created: function() {
        window.addEventListener('resize', this.handleResize);
      },
      destroyed: function() {
        window.removeEventListener('resize', this.handleResize);
      },
      methods: {
        handleResize() {
          this.width = window.innerWidth;
        }
      },
  };

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

Unveiling Three.js: Exploring the Unique One-Sided Surface

Here is the three.js code: <script type="text/javascript"> init(); animate(); // FUNCTIONS function init() { // SCENE scene = new THREE.Scene(); // CAMERA var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight; var VIEW_A ...

I need to find a way to properly test a recursive, async JavaScript function by utilizing fake timers

I've been working with a basic recursive function that performs as expected when run. To thoroughly test its operation at each stage, I want to utilize Sinon's fake timers. Unfortunately, it seems that the fake timers are only affecting the init ...

An Ajax call nested within another Ajax call

I've implemented an AJAX request to load my "home" page and "about" page into a designated "container" when a menu link button is clicked on my index.php. Now, I have three links on my "home" page and I want each of these links to open within the same ...

Encountered an issue while processing the firebase get request with the following error message: 'Unauthorized request in Angular'

Here are my rules: Utilizing a Firebase database Calling an API URL from this section https://i.stack.imgur.com/auAmd.png I am attempting to retrieve data from a Firebase API in an Angular application, but I keep encountering an 'Unauthorized reque ...

What is the best way to restrict the length and number of lines in a textarea based on pixel dimensions?

I am looking to create a textarea where people can select different fonts, such as "sans-serif" and "serif", to type in text. I plan to have buttons labeled "sans-serif" and "serif" that will change the font of the textarea when clicked. However, there ar ...

What makes NPM thrive while submodules struggle with construction?

My experience with utilizing npm has often involved encountering seemingly meaningless errors - such as Visual Studio projects failing to build and build tools (e.g. python.exe / CL.exe) being unavailable on the command line. For instance, some packages t ...

"Integration error: specified token_name parameters are invalid." FORTPAY INTEGRATION

I have been following the instructions provided by payfort in their email and referring to the Merchant Page 2.0 documentation for integration with nodejs. Despite sending all the necessary parameters in the request body, I encountered an issue where the T ...

Is there a way to manually stop a file upload (stream) using a XMLHttpRequest on the server?

Utilizing XMLHttpRequest (Level 2) to transfer a file to a node.js server, I am currently examining the file-stream for valid headers on the server side. The goal now is to halt the upload if any errors are encountered during streaming. My XMLHttpRequest c ...

Updating a specific row in a multiple row form can be achieved when the input field names match in a column

My task involves working with a report that generates a form in input mode. This form contains multiple rows of data, each row consisting of a button and an input field. The input field name remains consistent across all rows for easier processing by the C ...

The IP validation feature in the textbox is not performing as anticipated

My goal is to have a textbox that receives an IP address and validates it before submission. To achieve this, I've developed a JavaScript class called `validityCheck`. In my main Vue.js component, I aim to utilize this class to validate the input&apo ...

Is it possible to have two unique keys in a single MongoDB schema?

Currently attempting to achieve this functionality using mongoose: const newContent = new Schema({ heading: { type: String, unique: true }, url: { type: String, unique: true }, //... }); However, an error is being thrown: MongoError: E11000 dupl ...

The search filter in react material-table is not functioning properly upon initialization

Search functionality is functioning correctly in this code snippet: <MaterialTable columns={[ { title: 'Name', field: 'firstname', type: 'string' } ]} /> Unfortunately, the Search filte ...

Why is useEffect being executed twice?

For some reason, when I try to run useEffect for the first time page load, it ends up running twice. I can't seem to figure out why this is happening. Can someone please provide assistance? I'm currently using React 18 and I need help understand ...

The method by which npmjs.com evaluates the quality of code

After we release a package on npm, it provides us with insights such as popularity, quality, and maintenance on the search page (Refer to the example image below). I am particularly curious about how npm determines the quality metric. Any insights would be ...

What is the best way to utilize the `Headers` iterator within a web browser?

Currently, I am attempting to utilize the Headers iterator as per the guidelines outlined in the Iterator documentation. let done = false while ( ! done ) { let result = headers.entries() if ( result.value ) { console.log(`yaay`) } ...

Set up a trigger to activate when a WordPress User Role is selected, or alternatively, execute JavaScript

Looking for a solution to detect when a new user is created with a custom User Role set to lessee. Options include adding a trigger through WordPress filters or actions, or detecting the change in JavaScript using an event listener. I have identified the ...

Having difficulty changing the visibility of a div with Javascript

I've developed a piece of vanilla JavaScript to toggle the visibility of certain divs based on the field value within them. However, I'm encountering an issue where trying to unhide these divs using getElementById is resulting in null values. D ...

How can you maintain the "link" text in a div while removing the final hyperlink?

I am currently designing a breadcrumb navigation for a website. The breadcrumbs are generated using a templating language before the page is displayed. However, after rendering the page, I need to make some adjustments. Instead of using multiple IF/ELSE s ...

Is it possible to shift the image within the <canvas> element without having to redraw the entire canvas?

I created a game board and I am trying to implement drag-and-drop functionality for my pieces, which are in .gif format. However, I am struggling with finding a solution that allows me to move the pieces without constantly redrawing the entire board. Cur ...

Tips for combining Nuxt with Vue Cli 3

section: My current setup involves utilizing Nuxt.js to set up my Vue application. I'm curious if it's feasible to incorporate Nuxt into a Vue Cli 3 project in order to leverage the advantages of both platforms. Surprisingly, there doesn't ...