There seems to be a glitch with Vue computed as it continuously returns false instead of the

I am facing an issue where I need to add a specific class if a number is greater than 0 and another class if it is less than 0.

Here is the code snippet that I have been working on:

var prices = new Vue({
  el: "#prices",
  data: {
    message: "Hello Vue!",
    currencies: [],
  },
  computed: {
    color() {
      return this.price_change_percentage_1h_in_currency > 0 ? "inc" : "dec";
    }
  },
  // Fetching Data - DO NOT MODIFY
  mounted: function() {
    axios.get("https://api.coingecko.com/api/v3/coins/markets?vs_currency=eur&order=market_cap_desc&per_page=100&page=1&sparkline=false&price_change_percentage=1h%2C%2024h%2C7d")
      .then(response => {
        this.currencies = response.data;
        console.log(response);
      })
      .catch(error => {
        console.log(error);
      });
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<table id="prices">
  <tbody>
    <tr v-for="currency, index in currencies">
      <td v-html="index + 1"></td>
      <td :class="color">{{currency.price_change_percentage_1h_in_currency.toFixed(2)}}%</td>
      <td :class="color">{{currency.price_change_percentage_24h.toFixed(2)}}%</td>
      <td :class="color">{{currency.price_change_percentage_7d_in_currency.toFixed(2)}}%</td>
  </tbody>
</table>

Although the code appears to be correct with the computed property for adding classes based on conditions, it always applies the "dec" class to the table data, even when the value is greater than 0.

I hope someone can assist me in resolving this issue. Your help would be greatly appreciated.

Thank you.

Answer №1

Could you clarify what is meant by

this.price_change_percentage_1h_in_currency
?

In my view, it would be beneficial to create computed functions similar to this.

<td :class="color(currency.price_change_percentage_1h_in_currency)"></td>

methods() {
   color (currency) {
      return currency > 0 ? "inc" : "dec";
   }  
}

Answer №2

The parameter

this.price_change_percentage_1h_in_currency
is missing from your data.

To address this issue, consider using the following method:

methods: {
    color(price) {
      return price > 0 ? "inc" : "dec";
    }
  }

Ensure to send the price from the template as well.

Answer №3

Your computed function is making a reference to the variable

this.price_change_percentage_1h_in_currency
, which isn't defined in the data or passed through props.
Therefore, the default value for it will be undefined.

Based on the HTML code, it seems like

price_change_percentage_1h_in_currency
is a part of the object received in the response list from the API.

To address this, you can calculate the data within the `then` section of the API call.

mounted: function() {
    axios.get("https://api.coingecko.com/api/v3/coins/markets?vs_currency=eur&order=market_cap_desc&per_page=100&page=1&sparkline=false&price_change_percentage=1h%2C%2024h%2C7d")
      .then(response => {
        this.currencies = response.data;
        this.currencies.forEach(currency => {
          currency['color'] = currency.price_change_percentage_1h_in_currency > 0 ? "inc" : "dec";
        })
        console.log(response);
      })
      .catch(error => {
        console.log(error);
      });
  },

Then, in your HTML, you can use it like this:

<td :class="currency.color">{{currency.price_change_percentage_1h_in_currency.toFixed(2)}}%</td>

Answer №4

That's due to the color property being defined on the component itself, not on each individual currency object. All the created td elements will point to the same color property that is determined by using the

price_change_percentage_1h_in_currency
property on the component, which happens to be undefined as the component lacks this property.

To solve this, you can either add the color property to the currency objects when fetching them:

.then(response => {
  response.data.forEach(item =>
    item.color = item.price_change_percentage_1h_in_currency > 0 ? "inc" : "dec"
  );
  this.currencies = response.data;
})

Alternatively, it's better to compute the class in the template and add it to the parent tr element so you don't need to repeat it for each child td:

<tr v-for="currency, index in currencies" :class='[ currency.price_change_percentage_1h_in_currency > 0 ? "inc" : "dec" ]'>

Demo:

var prices = new Vue({
  el: "#prices",
  data: {
    message: "Hello Vue!",
    currencies: [],
  },
  computed: {
    color() {
      return this.price_change_percentage_1h_in_currency > 0 ? "inc" : "dec";
    }
  },
  // Getting the Data DO NOT TOUCH! :)
  mounted: function() {
    axios.get("https://api.coingecko.com/api/v3/coins/markets?vs_currency=eur&order=market_cap_desc&per_page=100&page=1&sparkline=false&price_change_percentage=1h%2C%2024h%2C7d")
      .then(response => {
        this.currencies = response.data;
      })
      .catch(error => {
        console.log(error);
      });
  },
})
.dec {
  background-color: #ffaaaa;
}

.inc {
  background-color:#aaffaa;
}

.as-console-wrapper {
  height: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<table id="prices">
  <tbody>
    <tr v-for="currency, index in currencies" :class='[ currency.price_change_percentage_1h_in_currency > 0 ? "inc" : "dec" ]'>
      <td v-html="index + 1"></td>
      <td>{{currency.price_change_percentage_1h_in_currency.toFixed(2)}}%</td>
      <td>{{currency.price_change_percentage_24h.toFixed(2)}}%</td>
      <td>{{currency.price_change_percentage_7d_in_currency.toFixed(2)}}%</td>
  </tbody>
</table>

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

JavaScript variable remains unchanged after AJAX call

I'm finding it difficult to fully understand variable scope in jQuery. I need some assistance in figuring out why the variable "final_shasign" works fine inside the AJAX but is undefined outside of it, even though it's declared beforehand. var f ...

Tips for updating a column with just one button in AngularJS

On my list page, there is an Unapproved button. I am new to angular and struggling to figure out how to retrieve the post's id and update the corresponding column in the database to mark it as approved. Can someone provide guidance on how to accomplis ...

Steps for implementing a select all feature with jQuery

I'm currently working on a jQuery function that is acting as a select-all option. Everything is functioning correctly except that when I deselect any of the child elements from select all, the option remains enabled. My goal is to enable or disable th ...

Exploring Laravel Eloquent using JSON and iteration methods

I need to extract specific fields from news articles and convert them into JSON format. My attempt to loop through all the news articles using this code: public function appNews() { $news = News::orderBy('id', 'desc')->get(); ...

How to load several Collada objects in THREE.js

When loading multiple car models using a loop in THREE.js, I've encountered an issue where sometimes all objects load correctly, but other times not all of them load. For instance, if the loop iterates 3 times, it may only load 2 objects at times, whi ...

Tips for transmitting data from a form to a server

I need assistance with sending form data to my backend server for a small website project. Although I have most of the backend work completed, I am struggling to figure out how to send the form data to the server. My goal is to send the data to a localhost ...

Encountering difficulties obtaining server response while utilizing dropzone.js version 4

I am currently using dropzone.js version 4 to facilitate file uploads from a webpage to my server. While the upload process is functioning properly, I am encountering difficulty in retrieving the server response. It should be noted that I am creating the D ...

Alias for JSON Schema Properties

Below is the JSON Schema that outlines a valid JSON structure for latitude and longitude coordinates: { "title": "coordinates", "type": "object", "properties": { "longitude": { ...

Guide on how to activate a css animation using pure vanilla javascript

Seeking a way to trigger a CSS animation using JavaScript without relying on frameworks like jQuery. I have successfully created the animation using @keyframes. Any suggestions? Below is the code snippet: /* Animations */ @keyframes party{ 0% {backgr ...

Parsing diverse types without assembly names, utilizing solely the Newtonsoft library

Upon receiving data from a service in JSON format, a part of the data consists of an object of class BASE. This BASE class has several derived classes: https://i.sstatic.net/fnCbQm.png The server now sends a fixed structure JSON, including an object of t ...

The hover effect is not functioning properly after loading jQuery with load();

When loading elements into a div using the load() function, I noticed that the :hover effect in CSS stops working for those elements. It's a dynamic menu setup, as shown below: <div id='main-menu'> <ul> <li class='click ...

Creating dynamic dropdown menus using JSON files in jQuery mobile is a useful technique for enhancing user experience on

I am working with a massive table (8 MBytes) that I need to filter using a small JavaScript application. The process works as follows: Countries Regions Skills I want the user to select one country, one region, and multiple skills as filters. Based on ...

Can the sidebar in Vue be toggled using a method?

In a <b-table>, I want to add an action button to each item: <b-table :items="data" :fields="fields"> <template v-slot:cell(actions)="data"> <b-button v-on:click="doSomething(data.index)"&g ...

Tips for verifying if JavaScript has modified HTML after receiving an AJAX response

We are experimenting with scraping a website using Selenium and Java. For example, we want to change the product color on this page. How can we determine when the website's JavaScript has altered the HTML after an AJAX response? And how long should we ...

Prevent scrolling after every time the mouse wheel is used

I have created a function that increments a class on a list item, here is the code snippet: var scrollable = $('ul li').length - 1, count = 0; $('body').bind('mousewheel', function(e) { if (e.originalEvent.wheelDelta / ...

Disabling the child element from triggering the parent element's onclick function, while still allowing it to respond to its own content

My list elements have onclick-functions that change the display of each element and its child div, moving them to the top of the list. Clicking again reverses this effect. The issue arises because the child div contains search fields, clickable pictures, ...

Struggling with getting the JavaScript, scss, and CSS television animation to turn on and off properly? Seeking assistance to troubleshoot this

After finding this javascript code on Codepen and seeing that it worked perfectly in the console there, I tried to run it on my computer with jQuery but it didn't work outside of Codepen. Even when attempting to use it on JSfiddle or compile the SCSS ...

What is the process for retrieving a list of files and folders from Google Drive within my Cordova PhoneGap Android application?

After completing the authentication process in my Cordova app, I receive the access token successfully. However, when I attempt to retrieve the file list using a specific method, I encounter the following error message: 403 Forbidden. "domain": "usag ...

The status of XMLHttpRequest consistently remains at 0

I want to incorporate the posts JSON from a wordpress.com site into another website, but I keep getting a status of 0 when making the request. This is the function I am using: var wordPress; var request = new XMLHttpRequest(); request.open("GET", "http ...

Await the sorting of intervals

Looking for a solution to re-execute a hand-made for loop with a delay of 10 seconds after it finishes indefinitely. I've attempted some code, but it keeps re-executing every 10 seconds rather than waiting for the loop to finish before starting again. ...