Vue.js fails to show Font awesome icon

Currently, I am attempting to incorporate a font-awesome arrow icon using my CSS code as seen below:

<style>
.negative {
  color: red;
}

.positive {
  color: green;
}

.negative::after {
  content: "\f106";
 }
</style>

Despite having font-awesome linked in my HTML through a CDN, the icon does not display correctly and just appears as a square. Could you provide any insights into why this is happening and offer suggestions on how I can resolve it?

Below is the rest of my code, outlining the process of displaying percentages:

<template>
<div>
 <v-data-table
      :headers="headers"
      :items="rowsToDisplay"
      :hide-default-footer="true"
      class="primary"
    >
      <template #item.thirtyDaysDiff="{ item }">
            <span :class="item.thirtyDaysDiffClass">{{ item.thirtyDaysDiff }}%</span>
            
      </template>
      <template #item.sevenDaysDifference="{ item }">
            <span :class="item.sevenDaysDiffClass">{{ item.sevenDaysDiff }}%</span>
            
      </template>
    </v-data-table>
</div>

</template>

<script>
import axios from 'axios';

  export default {
    data () {
      return {
        bitcoinInfo: [],
        isPositive: false,
        isNegative: false,
        headers: [
          {
            text: 'Currency',
            align: 'start',
            value: 'currency',
          },
          
          { text: '30 Days Ago', value: '30d' },
          { text: '30 Day Diff %', value: 'thirtyDaysDiff'},
          { text: '7 Days Ago', value: '7d' },
          { text: '7 Day Diff %', value: 'sevenDaysDifference' },
          { text: '24 Hours Ago', value: '24h' },
        ],
      }
    },

    methods: {
      
      getBitcoinData() {
        axios
      .get('data.json')
      .then((response => {

      var convertedCollection =  Object.keys(response.data).map(key => {
            return {currency: key, thirtyDaysDiff: 0, sevenDaysDifference: 0,  ...response.data[key]}
          })
          this.bitcoinInfo = convertedCollection
          
      }))
      .catch(err => console.log(err))
        },

       
      calculateDifference(a, b) {
      let calculatedPercent = 100 * Math.abs((a - b) / ((a + b) / 2));
      return Math.max(Math.round(calculatedPercent * 10) / 10, 2.8).toFixed(2);
    },

       getDiffClass(a, b) {
      return a > b ? 'positive': a < b ? 'negative' : ''
     },

     
       calculateSevenDayDifference(item) {

         let calculatedPercent = 100 * Math.abs((item['24h'] - item['7d']) / ((item['24h'] + item['7d']) / 2));
      return Math.max(Math.round(calculatedPercent * 10) / 10, 2.8).toFixed(2);
       }
      },
         computed: {
    rowsToDisplay() {
      return Object.keys(this.bitcoinInfo)
        .map(key => {
          return {
            currency: key,
            ...this.bitcoinInfo[key]
          }
        }).map((item) => ({
          ...item,
          thirtyDaysDiff: this.calculateDifference(item['7d'], item['30d']),
          thirtyDaysDiffClass: this.getDiffClass(item['7d'], item['30d']),
          sevenDaysDiff: this.calculateDifference(item['24h'], item['7d']),
          sevenDaysDiffClass: this.getDiffClass(item['24h'], item['7d']),
        }))
    }
  },
      mounted() {
        this.getBitcoinData()
      }
  }

</script>

Answer №1

Have you attempted importing your icons inside the template area using <i ...></i>?

Here is a working example. Visit the cdn.fontawesome/help-page for more information.

Vue.createApp({
  data () {
    return {
      isPositive: false,
      isNegative: true
    }
  }
}).mount('#demo')
.negative {
  color: red;
}

.positive {
  color: green;
}

.neutral {
 color: #666;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" rel="stylesheet"/>

<script src="https://unpkg.com/vue@next"></script>

<div id="demo">    
 <i class="fas" :class="isPositive ? 'fa-angle-up positive' : isNegative ? 'fa-angle-down negative' : 'fa-minus neutral' "></i> 
 <br>
 <br>
 <button @click="isPositive = !isPositive; isNegative = !isNegative" v-text="'change pos and neg'" />
</div>

Essentially, you'll bind the icon classes to your own conditions. You can write these conditions, for example, using the ternary operator within your template area. Hopefully, you understand the concept.

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

Navigating through different views in a Vue application using Vue Router directly from Vuex actions

Currently, I am in the process of developing a web application using Vue 2.x and Vuex 2.x. In this project, I need to retrieve some data from an external source via an http call. If this call fails, my objective is to redirect to a different page. GET_PET ...

Diverse Browser Outcomes with jQuery CSS

Currently, I am in the process of developing an app that utilizes percentages as offset positions for ease of calculation. For a visual example, you can visit this link: http://jsfiddle.net/WeC9q/1/embedded/result/ Although the zooming feature functions ...

Are web components capable of managing changes in CSS (maybe through cssChangedCallback)?

Is there a way to control the application of CSS to a web component similar to using attributes through attributeChangedCallback. I am currently developing a couple of web components that could benefit from being styled with CSS classes. However, I requir ...

What is the process to utilize Vue2 webcomponent slots within Vue3?

I am facing an issue with integrating a Vue2 web component, installed via NPM, into my new Vue3 project. The problem arises when trying to utilize the component's slots. Even though there are no errors in the following code snippet, the content insid ...

Is it truly impossible to align text around an image using flexbox?

In typical situations, you can easily float an image left or right to wrap text around it. However, in flexbox layouts, floating elements do not work as expected and finding a solution can be challenging. It is worth noting that Bootstrap 4 will be implem ...

Ways to transform a Vue-wrapped object into a standard object

I am trying to set the data variable of type object to a normal variable const myVue = new Vue({ el: '#myVue', data: { vars: {}, // show Form }, methods: { assign_vars() { const new_vars = this.vars; }, }, }); html ...

Looking to retrieve a cookie within Vue Router in Vue 3? Utilize the following approach within your router's `index.js

Scenario: Developing a Vue3 app with express as the API backend. Express utilizes express-sessions to create a server-side session that is transmitted to the browser and received in subsequent requests. I am in the process of implementing a route guard to ...

I'm having trouble adjusting the background color in the bootstrap template

------------ I am customizing the bootstrap SB Admin template for my asp.net core Identity project. However, I am facing an issue with changing the background color of the template and the navigation menu color. Even though I can see the color changes when ...

Open a new HTML page with jQuery with a click event trigger on an iframe element

Hello everyone, I have a simple question as I am still learning about Jquery. I am attempting to load another .html page whenever a figure element is clicked on this .html page. However, the script tag is not working as expected. Can someone please assist ...

Developing an interactive web interface with HTML

I've been attempting to design a flexible HTML page that replicates the layout of a Java applet clock, but I'm unsure if my current approach is correct. Below is an example of the three-clock image set that I am currently working on. My method i ...

What is the process of adding a newly uploaded file to an existing list of files using Vue?

I have implemented a file uploader that can accept a single CSV file and successfully POST it to the server using axios. However, I am facing difficulty in allowing users to upload multiple CSV files at different times, and have them added to the list of u ...

The CSS float is positioned beneath the Bootstrap navigation bar

Having an issue with the menu bars in my Rails 4 app. Specifically, I'm struggling with two divs overlapping. The goal is to align the "Register" and "Log In" blocks with the left-hand side menu while floating right. It should not float slightly belo ...

Blurring of text that occurs after resizing in CSS

When I use scale transform to zoom a div in HTML, the text inside becomes blurred. Is there a solution to make the text clear like the original? @keyframes scaleText { from { transform: scale(0.5, 0.5); } to { transform: scale(2, 2); } } ...

vue-router incorrectly updates parameters upon reload

One question I have is related to routing in Vue.js: // routes.js { path: '/posts', name: 'Posts', component: PostsView }, { path: '/post/:post_id', name: 'PostRead', component: PostReadView, }, { pat ...

Using JQuery to iterate through every unique div id in the HTML document

i am attempting to utilize jquery to iterate through each div tag that has an id of "rate". The goal is for jquery to execute a function on the individual divs. Here is my code snippet: information.html <html> <input class="rate" type="hidden ...

Ensure that the element remains on a single line, even if it needs to be positioned below

I am dealing with a row of horizontal divs that I want to keep together, but a floating element on the right side is causing them to break into two lines when it overlaps. My goal is to have the line of divs move below the float, similar to how the word "H ...

Challenge with Vue fetching data

I need to make an update request using fetch. Here is the code snippet: methods: { updateData() { fetch("http://localhost:3000/selectedData", { method: "PATCH", headers: { "Content-Type": & ...

What is the best way to address a NULL value within a VueJS filter?

This piece of code demonstrates a working filter filteredItems() { return this.items.filter(item => item.name.toLowerCase().indexOf(this.search.toLowerCase()) > -1) } However, my attempt to filter on a second column ...

Dynamically adjusting the width of an HTML element with ng-style using percentage values in AngularJS

I am facing a challenge where I need to display a progress bar in my UI based on a percentage value stored in a JSON response object. Here is an example of the JSON object: { completionPercent: 42 } The desired UI outcome should look like this: ┌ ...

Exploring the power of business logic with Vue 3 and Pinia

Imagine a scenario where I have developed a basic webshop application using Vue 3. Whenever a user adds an item to the cart, I store it locally in Pinia and also send this event information to the backend. Typically, what I would do is create an action in ...