Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue inline conditional if?

Tags:

vue.js

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?

like image 304
ThomasVdBerge Avatar asked Sep 25 '18 21:09

ThomasVdBerge


1 Answers

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>
like image 57
Steven B. Avatar answered Sep 30 '22 15:09

Steven B.