Search code examples
vue.jsstylesconditional-statements

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 = ...

Solution

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