Condition in v-bind:Style - VueJS

2019-03-19 05:37发布

I have an easy question for which I hope you could help:

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

I want the style attribute 'background' to return color if the URL from API is undefined

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

标签: vue.js vuejs2
3条回答
\"骚年 ilove
2楼-- · 2019-03-19 06:17

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'
     }
 }
查看更多
霸刀☆藐视天下
3楼-- · 2019-03-19 06:19

Finally I found it!

Use condition in V-bind:style VueJS:

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

==>

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

Hope it helps!

查看更多
聊天终结者
4楼-- · 2019-03-19 06:27

Feed Git's answer is perfect, here's another example with multiple attributes. Just separate with commas:

:style="[printing ? {'margin' : '0px 0px 20px 0px', 'min-height': '830px', 'box- shadow': 'none', 'border': 'none'} : {'margin': '0px 0px 20px 0px', 'min-height': '830px'}]

The form follows (for someone like me who's new at this):

:style="[boolVariable ? { true } : { false }]
查看更多
登录 后发表回答