Home > OS >  How do I change the color of a text in vue using ternary Operator?
How do I change the color of a text in vue using ternary Operator?

Time:07-31

I want to change the text color coming from the endpoint. It only display the value of the ternary operator on the UI ('backgroundColor:green). Can someone help me ?

mainTrack() {
 this.axios
    .get(
      `${configObject.apiBaseUrl}/Maintenance/Company`,
      configObject.authConfig()
    )
    .then((res) => {
     this.maintainTrack= res.data;

     this.maintainTrack.forEach(element => {
       element.isResolve = element.isResolve== 'true' ?  'backgroundColor:green' :  
        'backgroundColor:red'
            });
    })
    .catch((error) => {});
},

CodePudding user response:

Try to return a style object not a string :

  element.isResolve = { backgroundColor : element.isResolve ? 'green':'red' }

CodePudding user response:

You can add dynamic style in the HTML template itself.

:style="{'background-color': isResolve ? 'green' : 'red'}"

Live Demo :

new Vue({
  el: '#app',
  data: {
    isResolve: null
  },
  mounted() {
    // Updating isResolve value from API response.
    this.isResolve = true;
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <p :style="{'background-color': isResolve ? 'green' : 'red'}">{{ isResolve }}</p>
</div>

  • Related