Nicky Mirfallah
Nicky Mirfallah

Reputation: 1054

Condition on value for style on Vue.js

I'd like to check the value of my template

        <template slot="projected_end_date" slot-scope="{ line }">
            <datetime-display :value="line.projected_end_date"
                              type="date"
            style= "color: red"></datetime-display>
         </template>

and only set the style for red color when my value is less than current date. Any suggestion? I'm assuming it should be something like

value > DateHelper.now()? style = ...

Upvotes: 4

Views: 13834

Answers (2)

DobleL
DobleL

Reputation: 3918

Take a look at Class and Styles Bindings

You can use it like:

<div :class="{'my-class': myCondition}">

Simple example

new Vue({
  el: '#app',
  data: {
    selectedColor: 'red'
  }
})
.red { background: red}
.blue { background: blue}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>

<div id="app">
  <button @click="selectedColor='red'">Red</button>
  <button @click="selectedColor='blue'">Blue</button>
  <p :class="{red: selectedColor === 'red', blue: selectedColor === 'blue'}">the background color will change !</p>
</div>

Upvotes: 6

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

You can use class and style binding like this:

:style="value < DateHelper.now() ? { 'color': 'red'} : ''"

Or,

:style="{color: value < DateHelper.now() ? 'red' : 'inherit'}"

Or some default color:

:style="{color: value < DateHelper.now() ? 'red' : 'black'}"

But I suggest you to use class binding whenever possible:

:class="{warning: value < DateHelper.now()}"

And in your css styles:

.warning {
   color: red;
}

Also, you can simply use Date.now() instead of a helper function.

Upvotes: 7

Related Questions