Reputation: 8140
I have the following piece of code:
<div
:id="'object' + object.id""
:style="'position:absolute !important; width:' + object.width + '% !important; height:' + object.height + '% !important;'">
<div
This works fine and renders nicely as it should.
I now want to add conditional stuff in there. Something like
if object.background == 'solid'
background-color: #ffffff;
endif
I tried achieving this via the Vue inline if, which gave me this:
[object.background == 'solid' ? background-color: #ffffff important; : '']
But that just gave a lot of errors, which lead me to think I'm tackling this all wrong.
What would the correct approach be for me to achieve having short conditional statements in my style?
Upvotes: 5
Views: 24874
Reputation: 2972
I don't know if this should be marked as a duplicate of this question: Condition in v-bind:Style
However, this method is documented only for classes binding, on https://v2.vuejs.org/v2/guide/class-and-style.html
That said, you ask:
What would the correct approach be for me to achieve having short conditional statements in my style?
I don't think this is a correct approach. I mean, the correct approach would be to write css classes and apply them conditionally, since those are the documented methods, leave this for cases when you have to apply direct styling to override all other styles that apply to the element in question.
Other correct approach would be to use data
, props
, or even a computed property
or method
.
Also, you can have both style
and :style
attributes and vue will mix them for you, so you can define base style on the normal attribute and "other stuff" on the style binding.
But as i say, leave this for extreme cases where you really need this on the style attribute.
Upvotes: 4
Reputation: 9362
I would use a computed property that returns a style object.
new Vue({
el: "#app",
data: {
width: '200px',
height: '200px',
background: 'solid',
},
computed: {
styleObj() {
return {
position: 'absolute !important',
width: `${this.width} !important`,
height: `${this.height} !important`,
background: this.background === 'solid' ? 'green' : 'yellow',
};
},
},
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<div id="app">
<div :style="styleObj">
</div>
</div>
Upvotes: 7