What is the correct way to modify text color in Vue by utilizing the ternary operator?

Is there a way to change the text color that is being retrieved from the endpoint? Currently, it only shows the value of the ternary operator on the UI ('backgroundColor:green'). I need assistance with this. Can anyone help?

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) => {});
},

Answer №1

It is recommended to provide a style object instead of a string :

  element.hasColor = { color: element.isPressed ? 'blue':'yellow' }

Answer №2

One interesting feature is the ability to include dynamic styles directly in the HTML template.

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

Check out this Live Demo :

new Vue({
  el: '#app',
  data: {
    isResolve: null
  },
  mounted() {
    // Updating isResolve value based on 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to dynamically write a knockout data binding event using jQuery?

let $button = $('<input/>').attr({ type: 'button', value: data.styleData, id: buttonId, data - bind: event: { click: $parent.submitPopUp } }); An error is being displayed. ...

Caution: Take heed when accessing an Excel file exported from an HTML table

I have encountered an issue while using the code below to download a file with .xls extension. Upon opening the downloaded file, I am prompted with a warning message: The file you are trying to open, 'Statement.xls', is in a different format t ...

embed a hyperlink onto a live video at a designated moment within an HTML document

Can anyone help me figure out how to overlay a link over a video playing at a specific time on an HTML page? I know it's easy to do on Youtube, but I need to accomplish this task without using Youtube. :) Thank you in advance for any assistance! ...

How come AngularJS $onChanges isn't able to detect the modification in the array?

What is the reason behind Angular's failure to detect changes in an array, but successfully does so after changing it to null first? In my AngularJS component, I utilize a two-way data binding to pass an array. The parent component contains a button ...

`Could not locate JavaScript files within the _nuxt directory`

I encountered a strange issue with my Nuxt 2.15.4 project. While the code was functioning perfectly locally (<--dev & build-->), it fails to load correctly on the server after the build process. The error message I am seeing is: GET https://example.c ...

Trouble with JavaScript confirm's OK button functionality in Internet Explorer 11

Having trouble with the OK button functionality on a JavaScript confirm popup in IE11. For one user, clicking OK doesn't work - nothing happens. It works for most other users though. Normally, clicking OK should close the popup and trigger the event h ...

json evaluation causing an issue

When trying to use eval for the JSON below, I am encountering a syntax error with the message: Expected ']'. I am unsure of what is missing in my code. Here is my JavaScript statement: eval('var jsonResponse = ('+response+')' ...

Tracking the progress of reading position using Jquery within an article

Here is an example of a reading progress indicator where the width increases as you scroll down the page: http://jsfiddle.net/SnJXQ/61/ We want the progress bar width to start increasing when the article content div reaches the end of the article c ...

Utilizing async/await in JavaScript within a class structure

I am facing a dilemma in using the new async/await keywords within the connect method of my JavaScript class. module.exports = class { constructor(url) { if(_.isEmpty(url)) { throw `'url' must be set`; } ...

The blending of Angular 4 HTTP responses creates a jumbled mess

I have encountered an issue while using Angular 4 across different browsers like safari, chrome, and Firefox. In my Angular 4 application, I am sending XHR Requests via httpclient to interact with a REST service. The communication is done in JSON format. ...

What is the best way to retrieve data from a getter within a namespaced module using vuex?

My module includes: export default { namespaced: true, state: { conversations: false }, getters: { getConversation(state, ConversationId) { console.log('here i am!') let conversation = _.fi ...

The conversion of a 2D json array into a string is mistakenly performed

On hand is an outer array that contains 2 arrays within it, making it a 2-dimensional array. This is how the array is initialized: $outerArray = array(); $nestedArray = array("first", "second", "third", "fourth"); $outerArray[] = $nestedArray; $nest ...

Utilizing underscore.js to aggregate data points: A comprehensive guide

If I have an array containing 6 numeric data points and I want to transform it into a new array with only 3 data points, where each point is the sum of two of the original points. For example: [1,1,1,1,1,1] would become [2,2,2] What would be the most eff ...

Experiencing a 404 Error with a Specific Route in Node.JS Express

I'm running into some issues with my node.js express routes. As a beginner, I'm having trouble spotting where I've gone wrong. Despite looking at similar threads on Stackoverflow, I haven't been able to fix the problem. Is there anyone ...

Screen Tearing in Threejs Custom Shader Implementation

For my tilemap implementation using Threejs and the custom shaders by Brandon Jones found here, I am utilizing a THREE.Plane geometry for each layer. The face of the plane is painted with the following vertex and fragment shaders: Vertex Shader: var tile ...

Is it possible to achieve consistent scrollY height values across various screen sizes?

Looking to apply a class when a certain screen height is reached? Here's my approach: window.onscroll = function() {scrollPost()}; function scrollPost () { var x = window.screen.width; var i = window.scrollY; var a = i / x; animator ...

What is the recommended way to retrieve the Nuxt `$config` within Vuex state? Can it only be accessed through store action methods?

After using the dotenv library for my .env file, I had to change the runtimeConfig in order to secure my project's secret key. In my most recent project, I utilized nuxt version "^2.14" in SPA mode, so I only utilized "publicRuntimeConfig" in my nuxt ...

Can the button run a Python script with the help of jQuery?

I'm currently working on setting up a website using a RaspberryPi. I've managed to integrate JustGage for reading temperatures and other sensors in real-time. Now, I want to add a button that when pressed will execute a Python script. Here' ...

Implementing global parameters in ui-router

Currently, I am utilizing ui-router in AngularJS as shown below: .state ('browse.category', { url: "/:category", templateUrl: "views/browseCategory.html", controller: function($stateParams, $scope) { $scope.params = $st ...

EmberJS - how to register a precompiled handlebars template

In my EmberJS application, I have precompiled all of my handlebars templates so that they are loaded as pure Javascript files. However, I am encountering an issue where these precompiled templates are not being added to the Ember container as expected. In ...