Condition in v-bind:Style - VueJS

Use condition in V-bind:style VueJS:

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

Here is the minimal example,

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

If you need Parent-Child-Conditions, then this is the magic:

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

In short of:

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

Hope it helps!


The previous references were very good, but for me what really worked was this:

<input type="text" 
v-bind:style=" boolVariable ? 'border: 1px solid orange;' : 'border: none;' ">

In the documentation: https://vuejs.org/v2/guide/syntax.html#Using-JavaScript-Expressions

Regards!


Use a computed property for this:

<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
    }
}

Edit:

I'm making a bunch of assumptions here with your API and routes. This is a rough stab at generalizing it:

<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'
     }
 }

Tags:

Vue.Js

Vuejs2