2

I have a table and I want to change the class depending on the value.

My first approach was to use v-bind:class="{} this will change to the right class if true. However doing like this I should create new elements for each value on my table which doesn't look like the best option.

Is there a way to use conditionals, like if {{value}} > 5 class:something

I wrote a small jsfiddle with how I got it working right now. The idea is that each element in the table will follow these rules without the need of write an if statement for each cell:

  if (this.v1 < 4) {
    this.goodBox = true
  } else if (this.v1 < 6) {
    this.goodBox = true
  } else {
    this.badBox = true
  }

2 Answers 2

1

I'm guessing a little on your intent, but something like this.

changeClass(value) {
  return {
    'good_box': value <= 4,
    'medium_box': value > 4 && value <= 6,
    'bad_box': value > 6
  }
}

Template

<table style="width:100%; border:1px solid black">
  <tr>
    <td :class="changeClass(v1)">{{v1}}</td>
    <td :class="changeClass(v2)">{{v2}}</td>
  </tr>
  <tr>
    <td :class="changeClass(v3)">{{v3}}</td>
    <td :class="changeClass(v4)">{{v4}}</td>
  </tr>
</table>

Updated fiddle.

Sign up to request clarification or add additional context in comments.

Comments

0

I would use v-for:

<div id="app">
  <table style="width:100%; border:1px solid black">
      <tr v-for="v in values" v-bind:class="{ good_box:v < 4, medium_box:v < 6, bad_box:v >= 6}">
        <td>{{v}}</td>
      </tr>
  </table>
</div>

And simpler app:

var test = new Vue({
  el: '#app',
  data: { 
    values:[
      3,
      5,
      20,
      15],
  },
});

fiddle

Of course you can do two v-for, to generate rows and columns, and modify your data to suit you needs.

You could also use methods for conditionals, but it's up to you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.