How to dynamically set a computed background image in Vue 2

I have several divs that I want to style with backgrounds from values stored in an array. My attempt to set the background overlay for each one by creating a computed property has not been successful:

 computed: {
      backgroundImage(url) {
        let overlay = 'linear-gradient(270deg, rgba(0, 0, 0, .5), rgba(0, 0, 0, .5))';
        return 'background-image:'+ overlay +' , url(' + url + ');';
      }
    }

I tried passing the URL like this to the computed property:

:style="{ backgroundImage: url(`${articles[0].image.src}`) }"

However, this approach is not returning the computed value as expected. How can I resolve this issue?

Answer №1

When it comes to a computed property :

computed: {
    displayBackgroundImage: () => (url) => {
        let overlay = 'linear-gradient(270deg, rgba(0, 0, 0, .5), rgba(0, 0, 0, .5))';
        return 'url("' + url + '"), ' + overlay;
    }
}

As for methods:

methods: {
    showBackgroundImage(url) {
        let overlay = 'linear-gradient(270deg, rgba(0, 0, 0, .5), rgba(0, 0, 0, .5))';
        return 'url("' + url + '"), ' + overlay;
    }
}

Here is how you can use it :

:style="{ 'background-image': showBackgroundImage(articles[0].image.src)}"

Answer №2

When your data remains constant and the background doesn't change, you can easily set the background using this method:

:style="{ background: `url(${articles[0].image.src})`}"

If the articles need to be computed first, then you can include that process or other values in your computed object

 computed: {
   backgroundImages() { 
     const overlay = 'linear-gradient(270deg, rgba(0, 0, 0, .5), rgba(0, 0, 0, .5))';
     return articles.map(article => 'background-image:'+ overlay +' , url(' + articles[0].image.src + ')');
   }

And then use it like this:

:style="{ background: backgroundImages[0]}" 

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

Finding the index of an element in an array using the filter method in Angular JavaScript

As I was working with an array of pages in a book, I wanted to find the index of a specific page that had been identified using filter. While my current function gets the job done, I can't help but wonder if there's a way to combine indexOf or fi ...

Use ng-class in a P tag to assess a variety of expressions

Is there a way to apply ng-class to automatically evaluate negative values within a < p > tag? <p <strong>LW$:</strong> {{d.lw_metric}} <strong>LW:</strong> {{d.lw_metric_percentage}} <strong>L4W:</strong> {{d.l ...

Converting timestamps: Retrieve day, date, hour, minutes, etc. without utilizing the "new Date()" function

Currently developing a web-app and faced with the challenge of displaying items in a list correctly. I am working on converting the timestamp attached to each item into a readable format. For instance, 1475842129770 is transformed into Friday, 07.09.2016 ...

How can one generate an HTML element using a DOM "element"?

When extracting an element from an HTML page, one can utilize a DOM method like .getElementById(). This method provides a JavaScript object containing a comprehensive list of the element's properties. An example of this can be seen on a MDN documentat ...

interactive navigation menu with countdown feature

Looking to create an HTML/jQuery dropdown menu, but encountering a problem. The goal is for the div to slide down when the mouse hovers over the "games" navigation button and only disappear after 5 seconds of the mouse being out, not instantly. Here's ...

What is the best way to display an HTML file in Express when utilizing React as the frontend?

As a newcomer to the world of web development, I'm facing a seemingly simple issue that is consuming much of my time. I have set up an express server to run React on the front end. To achieve this, I use webpack and bundle to parse my react app, and ...

Issues with Rails not successfully sending AJAX data to the controller

I am new to AJAX, so please bear with me while I try to figure this out. My goal is to send data from a chat message box to two places – the chat box itself and to a method in my Rails backend. This way, I can display the message in real-time and also st ...

First render does not define useEffect

Why am I experiencing an issue here? Whenever I attempt to retrieve data from my API, it initially returns undefined during the first render, but subsequent renders work correctly. const [data, setData] = useState([]) useEffect(() => { const fe ...

The presence of an unauthorized token within the meteor/node module has been detected, specifically related

While following g00glen00b's tutorial on meteor/twitter integration (), I encountered a persistent error. Any assistance or clues would be greatly appreciated. Steps I've Taken Uninstall/reinstall npm Uninstall/reinstall twitter package Uninst ...

What strategies can I implement to ensure my modal dialog box remains responsive? Adjusting the window size causes the modal box to malfunction and lose its structure

Whenever I adjust the size of the browser window, the elements inside the modal box become misaligned. HTML <div class='modal'> <div class='modal-content'> </div> </div> Below is the CSS for the modal ...

Tips for incorporating VueJS 2 global components within single file components

As I attempt to utilize a globally registered component (using Vue.component) within a single file component, I consistently encounter the following warning: vue.common.js:2611[Vue warn]: Unknown custom element: <my-component> - did you register the ...

Add the $scope ng-click event to a previously hidden element once it becomes visible

If you need a clearer explanation, feel free to ask. I have incorporated a global search function into the header of my website. I am looking to show a separate input box for mobile search that utilizes the same ng-click event, but the input field remains ...

Vue.js: Utilizing async/await in Vue.js results in an observer being returned

Currently, I'm attempting to retrieve data from an API and store it in an array. The issue arises when I try to log the response data from the API - the data is displayed just fine. I assign the value of a variable to the data obtained from awaiting t ...

Calculating the total of fields from populated documents using Mongoose

In my application, I have two main models: User and Track. A User can complete various Tracks and earn points for each one. The schema for the User model looks like this: let userSchema = new mongoose.Schema({ name: {type: String, required: true}, ...

When the button is clicked, redirect to a new page and submit a form using AJAX with data obtained from the click event

I have a page called 2.html where inputting an ID number results in some output being displayed. This functionality is achieved using Ajax post method, sending data along with the data parameter. I also have another page named 1.html that contains a list o ...

Property that is dynamically populated based on data retrieved from an external API

My template relies on an API call (Firebase) to determine the return value of my computed property, which in turn decides whether certain elements are displayed. However, I've noticed that my computed property is not reactive - its value in the templ ...

Can Vue-router be used to load screens into Tabs?

In my setup, I have a routes file with multiple routes configured such as localhost:8000/test and localhost:8000/test2. My objective is to create a final route like localhost:8000/tabs, where I can utilize a tab library like bootstrap or Vuetify to displa ...

Is there inconsistency in the behavior of json.parse when given the same input?

This query pertains to the differentiation in outputs resulting from various inputs I am not seeking guidance on achieving a specific output. The reason behind the discrepancy in output between two scenarios, despite using the same argument for the JS ...

true not redirecting to 404 page when axios request fails

I have implemented Axios to access a basic API. My goal is to direct the user to the default Next.js 404 page in case of a failed request with a 404 error code. I have set the notFound boolean to true if the request status is 404. There are a total of 10 u ...

Filtering deeply nested arrays

Hey, I'm working with this interesting array: [ { "Navn": "Long Island Iced Tea", "Nummer": "2", "Glas i ml": "250", "Instruktioner": "", "a": "Hæld is i glasset", "b": "pynt med en skive lime", ...