Josh Gilbert
Josh Gilbert

Reputation: 89

Changing text color with a function in vue

I have this line

<th style="text-align: center; color: cycleTimeColorStat([S5MachLive,70])" {{ S5MachLive }} </th>

Where {{ S5MachLive }} is my shown value cycleTimeColorStat is this function

cycleTimeColorStat(time, num) {
      try {
        if (time !== 0) {
          return "yellow";
        } else {
          if (time < num) return "green";
          else {
            return "red";
          }
        }
      } catch (error) {
        return "yellow";
      }
    },

What I'm trying to do is call the function to evaluate for color and then return the color and render the value in that color

Upvotes: 2

Views: 4140

Answers (2)

MaBbKhawaja
MaBbKhawaja

Reputation: 902

Just add your function into computed lifecycle hook and it will solve the problem

<th style="text-align: center; color: cycleTimeColorStat([S5MachLive,70])" {{ S5MachLive }} </th>

<script>

export default {
  computed: {
    changeColor(time, num) {
      try {
        if (time !== 0) {
          return "yellow";
        } else {
          if (time < num) return "green";
          else {
            return "red";
          }
        }
      } catch (error) {
        return "yellow";
      }
    }
  }
};
</script>

<style scoped>

</style>

Upvotes: 0

omerS
omerS

Reputation: 874

A simple solution: You can bind a class to your th element and make a method to change it's class.

<th :class="changeColor(S5MachLive,70)" > {{ S5MachLive }} </th>

<script>

export default {
  methods: {
    changeColor(time, num) {
      try {
        if (time !== 0) {
          return "yellow";
        } else {
          if (time < num) return "green";
          else {
            return "red";
          }
        }
      } catch (error) {
        return "yellow";
      }
    }
  }
};
</script>

<style scoped>

.yellow {
  color: yellow;
}

.green {
  color:green;
}

.red {
  color: red;
}

</style>

Upvotes: 3

Related Questions