In the v-bind:Style statement, check the condition

<div>
  <figure :style="{ 'background': 'url(' + item.main_featured + ') center no-repeat' }">
</div>

I need the background style attribute to display a color if the URL fetched from the API is undefined

For example:

If item.featured_photo is not null:

<figure style="background: url('localhost:6969/image.img') center no-repeat">

If item.featured_photo is null:

<figure style="background: #FFF">

Answer №1

Utilizing conditional statements in V-bind:style with VueJS:

v-bind:style= "[condition ? {styleA} : {styleB}]"

Below is a simple example,

<figure :style="[item.main_featured ? {'background': 'url(' + item.main_featured + ') center no-repeat'} : {'background': '#FFF'}]">

If you require Parent-Child-Conditions, this is the trick:

v-bind:style= "[condition_1 ? condition_2 ? {styleA} : {styleB} : {styleC}]"

In summary:

if (condition_1) {
   if (condition_2) {
      return styleA
   } else {
      return styleB
   }
} else {
  return styleC
}

Answer №3

Here's an excellent example of how to use multiple attributes in Git's answer, presented in a clear and concise manner:

:style="[when separating with commas, you can easily include various attributes such as 'margin', 'min-height', 'box-shadow', and 'border'. For example: {'margin' : '0px 0px 20px 0px', 'min-height': '830px', 'box-shadow': 'none', 'border': 'none'} ]

For those who are new to this concept, the form typically looks like this:

:style="[conditional statement ? { true } : { false }]

Answer №4

Utilize a computed property in this scenario:

<figure :style="'{ background: `${background}` }'">

...

data () {
    return {
        item: {
           featured_photo: null
        }
     }
},
computed: {
    background () {
        return !item.featured_photo ? '#fff' : `url(${item.featured_photo}) center no-repeat`
    }
},
methods: {
    setPhoto(val) {
         this.item.featured_photo = val
    }
}

Revise:

Assumptions have been made regarding your API and routes. Here is a generic approach:

<figure :style="'{ background: `${getBackground('main_featured')}` }'">
<figure :style="'{ background: `${getBackground('featured_photo', 1)}` }'">
<figure :style="'{ background: `${getBackground('featured_photo', 2)}` }'">


...

methods: {
     async getBackground (type, index) {
          let r = await axios.get(`/images/${type}/${index}`).then(r => r.data.background)
          return r || '#fff'
     }
 }

Answer №5

It was successful in my case

<div :style="[ myboolean ? { backgroundImage: `url(${group.backgroundImage.sourceUrl})` } : null ]">

Answer №6

If you find yourself in need of applying

several conditional style bindings
to a single element, you can utilize the following approach:

:style="[ 
    condition1 ? { 'width': '50%' } : '', 
    condition2 ? { 'height' : '20rem' } : ''
]"

Answer №7

When iterating through an object, a method can be used to determine the style based on a property within the object. In my experience, this has been the only solution that actually works when none of the other options seem to do the job.

<div v-for="thing in things">
   <div :style="'{ background: `${background(thing)}` }'"></div>
</div>
...

data () {
    return {
        item: {
           featured_photo: null
        }
     }
},
methods: {
    background (thing) {
        return thing ? 'red' : 'black'`
    }
}

Answer №8

When it comes to setting the Background Color, it's crucial to be mindful avoid using

:style="[ isDark ? {background-color: 'black'}: {background-color: 'white'}]"

This method will not yield results; instead, opt for backgroundColor

:style="[ isDark ? {backgroundColor: 'black'}: {backgroundColor: 'white'}]"

Answer №9

When using the Quasar framework, you can adjust styles dynamically based on the screen size:

V-bind:style="$q.screen.lt.md ? 'height:600px' : ''"

Answer №10

If you're looking to incorporate more than just Boolean conditions and also include numerical values, this solution proved effective for me.

:style="{ transform: `translate(${x}vw)` }"

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

Combining the keys of two objects in JSON

console.log(a) ; // output in console window= 1 console.log(b);// output in console window= 2 var c = {a : b};// Is there a better way to do this? var d = JSON.stringify(c); d = encodeURIComponent(d); I want the final value of d to be {1:2}. ...

Is the file corrupt using node.js?

Looking for ways to determine if a file is corrupted using node.js? I have attempted various File System methods, such as fs.readFile, fs.open, and fs.access, but all of them are showing an OK status. However, I am confident that my file is corrupted base ...

Comparing Embedded and Linked JS/CSS

In my experience, I understand the advantages of using linked CSS over embedded and inline styles for better maintainability and modularity. However, I have come across information suggesting that in certain mobile web development applications, it may be m ...

Stopping the papaparse streaming process once a certain number of results have been achieved

Currently, I am utilizing the PapaParse library to parse a large CSV file in chunk mode. During my data validation process, I encountered an issue where I was unable to stop streaming the data once validation failed. I attempted to halt the streaming by ...

Having difficulty getting a basic code to work: ajax method ($.post) with MySQL is not

I am facing an issue with this code not functioning properly. I want to display the result of a MySQL query without sending any data using my simple Ajax code. $('.myClass').on('click',function(){ $.post('resultAll.php'); ...

Is there a way to transform a local array into remote JSON data?

I am attempting to retrieve an array from a remote server that is connected to a dynamic database. From what I have gathered on Ionic forums, it seems that I need to utilize the $http function from AngularJS. However, since I am new to AngularJS, the curr ...

Please provide both an image and text in addition to a progress bar by using the form to

I am working on a form that needs to store both images and text data in a database. <form action="processupload.php" method="post" enctype="multipart/form-data" id="UploadForm"> <input name="name" type="text" /> <input name="age" ty ...

Exploring the function.caller in Node.js

Currently, I have a task that relies on function.caller to verify the authorization of a caller. After reviewing this webpage, it seems that caller is compatible with all major browsers and my unit tests are successful: https://developer.mozilla.org/en-U ...

Is it possible that the background color won't change on the second click?

Initially, my first click worked fine and successfully changed the background color. However, as soon as I added a second condition, it stopped working. var showBox = $('.show'); showBox.click(function(){ if (parseInt($(this).attr('v ...

Guide to integrating and utilizing a personalized JavaScript file within TypeScript components in an Angular 2 application

I have created a standard Angular 2 App using angular-cli. Now, I am trying to incorporate a custom .js file into it. Here is a simplified version of what the file looks like: 'use strict'; var testingThing = testingThing || {}; testingThing. ...

Leveraging Vue mixin within a @Component

After implementing the vue-property-decorator package, I encountered an issue when trying to use a mixin method inside the beforeRouteEnter hook. Here is what I initially tried: import { Component, Mixins } from 'vue-property-decorator'; import ...

Typescript: The type 'X' does not correspond with the signature '(prevState: undefined): undefined' in any way

My React Native app, which is written in TypeScript, has been giving me a hard time with an error lately. The issue revolves around a Searchable List feature. This list starts off with an Array of values and gets updated when users type into a search bar. ...

Focus on an element in ThreeJS

Is it possible to adjust the zoom direction in three.js so that it zooms towards the mouse cursor? I'm having trouble finding where to change the zoom target for this specific feature. ...

Embed the website onto a webpage using ajax or an iframe without any need for navigation

I have a unique challenge ahead. Imagine there are two websites, one is a web page and the other is hosted within the same domain. My goal is to load the entire second website into a div or iframe of the first web page, similar to how a free proxy browser ...

The difference between using document.getElementsByTagName("img") and document.getElementById('testimg')

My HTML code is as follows: <a href="index.php"><img id="testimg" src="images/logo.png"/></a> This is my JavaScript code: function getW(){ var theImg = document.getElementById('testimg'); return theImg; } theImg = ...

Having trouble with the nav-item dropdown functionality on Laravel Vue?

Currently utilizing Laravel and Vue.js along with AdminLTE. Initially it was functioning properly, but now... head <!-- Font Awesome Icons --> <link rel="stylesheet" href="plugins/fontawesome-free/css/all.min.css"> <!-- Theme style --> ...

Utilize the atan2() function to rotate a div so that it follows the movement of the mouse

I am trying to create an effect where the mouse aligns with the top of a div and the div rotates as the mouse moves. The rotation should happen when the top part of the div is in line with the mouse cursor. My goal is to achieve this using the atan2 functi ...

Guide to retrieving a user's current address in JSON format using Google API Key integrated into a CDN link

Setting the user's current location on my website has been a challenge. Using Java Script to obtain the geographical coordinates (longitude and latitude) was successful, but converting them into an address format proved tricky. My solution involved le ...

What methods can I use to stop the styles of a child component from impacting those of the parent component

Is there a way to create CSS rules that achieve the following conditions? The parent component's CSS does not impact the child component The child component's CSS does not affect the parent component The child component is sourced from an exte ...

Output a variable that is generated from invoking an asynchronous function

I'm currently in the process of developing an application that is going to leverage the capabilities of a SOAP server through the use of the https://github.com/vpulim/node-soap module. One of the main challenges I am facing is how to efficiently crea ...