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

Vue JS Meta Tags not displaying images on Open Graph

As a blog designer, I am interested in optimizing the preview image when sharing my posts on social networks, similar to how it appears on Medium's posts. <meta property="og:image" content="https://medium.com/js-dojo/getting-your-head-around-vue-j ...

Vue component encounters issue with exporting JavaScript functions

I decided to streamline my code by moving some functions into a JavaScript file like this: [...] function changeToEditView(reportId) { let pathEdit="/edit/"+reportId; this.$router.push({ path: pathEdit, replace: true }); } [...] export {c ...

Display scrollable content at the bottom

I am currently working on creating a chat application using JavaScript (AngularJS without jQuery) and I am wondering if it is possible to have a scrollable div load to the bottom automatically. While I am familiar with the scrollTo JS property, I do not f ...

Fetching data in VueJs before redirecting to a new page

Within the mounted function, I am creating an action that fetches data from a Rest API and populates my table in a Vue.js component mounted() { UserService.getProjects().then( (response) => { this.isProject = true; this.project ...

Why do React components require immutable props when values are passed by value regardless?

I am not deeply knowledgeable in JavaScript, so I have been experimenting with some code: var demo = 'test'; var obj = { x: 'abc' } function foo(str) { str += '_123'; ...

Creating an inverted curve or border-radius for a div element is a design technique that can add

I've been tackling a project that requires me to style the border of a div in an inverted manner. To achieve this, I'm limited to using only CSS and JS without any plugins. I've searched through various online resources and similar questions ...

Shut down the tab or browser window containing information on vue

When attempting to log off a user by closing the page and browser, I encountered difficulty. 1. window.onunload; 2. window.onbeforeunload. window.onunload = function() { differTime = new Date().getTime() - beginTime; if (differTime <= 5) { cle ...

Fade effect on content in Bootstrap carousel

I am currently making some updates to the website mcelroymotors.com. One issue I have encountered while working on the homepage carousel is that the caption only pops up on the first slide, and does not appear on any of the subsequent slides. I would lik ...

What is the best way to create a screen capture of a webpage using a URL?

Currently working on a Spring MVC website project, I have implemented a form requesting the user's website URL. Once entered, I aim to display a screenshot of the specified website for the user to view. Contemplating whether to generate the image on ...

Restricting the amount of requests per user within a single hour [Node.js]

As I work on developing a server side application using Nodejs and Express, one thing that crosses my mind is limiting the number of requests per user within a specific time frame to prevent malicious hackers from overwhelming the server with spam. I&apos ...

What is the process for retrieving user data from Postgresql using axios.get when the data is already stored within the database?

Using auth0 for user sign up, my React app automatically retrieves user information upon logging in and sends a POST request with axios to the backend. The user ID is stored in userId and the user information is stored in currUser. However, upon logout and ...

Utilize a function as a parameter

I am struggling to figure out how to make this function pass by reference in my code. Is there a way to achieve this? var Class = function() { var callback1; var callback2; function buildStuff(data, callback) { element.onclick = funct ...

Concealing applicationId and clientToken in Datadog

I'm currently using an Angular application and I've integrated it with the Datadog application to utilize Session and Replay (RUM). However, I am concerned about the security of my sensitive information such as applicationId and clientToken. Is t ...

Encountering a proxy error while attempting to create an account or log in, with no network

Embarking on my first web development journey, I utilized React-Redux to craft a React.js application within the client folder. For the backend code, I employed Node.js and MongoDb as my database. This project represents a significant milestone in my lear ...

Using Laravel and Vue to make a POST request to an API endpoint, we utilized a web route instead

Currently, I'm in the process of creating a multi-page application using Laravel and Vue.js. I recently built a form that posts to an API route. Initially, everything was functioning properly when I tested it on my homepage. However, after relocating ...

Setting model value in Angular 2 and 4 from loop index

Is it possible to assign a model value from the current loop index? I've tried, but it doesn't seem to be working. Any suggestions on how to achieve this? Check out this link for my code <p *ngFor="let person of peoples; let i = index;"& ...

Removing a row from MySQL using JQuery Ajax

Hello there! I'm currently facing an issue while trying to remove a row from a MySQL database using PHP and AJAX. I initially thought it would be a simple task with $.ajax {}, but unfortunately, the row is not getting deleted for some reason. Here&apo ...

Utilizing MutationObserver in JavaScript for Streamlined Code Execution

One of my functions utilizes a MutationObserver to track attribute changes in a specified element and logs them to the console. Below is an example where I pass 'card' elements in a foreach loop: track_attr_changes(element); The parameter ' ...

Is CDATA insertion automatic in JavaScript within Yii framework?

Currently I am working with Yii and have noticed that whenever I insert any JavaScript code, it is automatically encapsulated in CDATA. I am curious as to why this is happening. Will there be any issues if I were to remove the CDATA tags, considering that ...

What is the method for assigning a string to module variable definitions?

As someone new to TypeScript and MVC, I find myself unsure if I am even asking the right questions. I have multiple TypeScript files with identical functionality that are used across various search screens. My goal is to consolidate these into a single fil ...