Unable to implement styles or classes in Vue.js when utilizing it in a loop

My code has a feature where item.fav starts as false, but changes to true when a button is clicked. I want the color of the icon to turn purple when item.fav is true, but it's not working as expected.

 <template>
      <v-container fluid>
        <v-row>
         <v-col v-for="(item, index) in items">
          <v-btn icon @click='changeFav(item)'>
           <v-icon :style='{color:`${fillcolor(item)}`}'>mdi-heart</v-icon>
          </v-btn>
         </v-col>
        </v-row>
      </v-container>
    </template>
<script>
 export default {
  ....,
  methods: {
   fillcolor(item){
    return item.fav ? 'purple' : 'orange';
   },
   changeFav(item){
     item.fav=true;
   },
  }
</script>

I also attempted to use a class

.....
<v-icon class='{fillColor: item.fav}'>mdi-heart</v-icon>
.....

<style>
.fillColor {
color: 'purple';
}
</style>

Using a data variable as the condition works, but I can't do that in this loop. What am I doing wrong here or how can I do it better?

Answer №1

For more information on Class and Style Bindings, click here

Here is an example of how to implement it

<script setup>
  import {ref} from 'vue'
const toggleFavStatus = (element) => {
     element.favorite = !element.favorite;
   }

const elements = ref([
  {name: "test1", favorite: false},
  {name: "test2", favorite: false},
  {name: "test3", favorite: true},
  {name: "test4", favorite: false},
  {name: "test5", favorite: false},
  {name: "test6", favorite: false},
  {name: "test7", favorite: false},
])
</script>

<template>
  <div v-for="(element, index) in elements" :key="index" @click="toggleFavStatus(element)" >
    <span :class="[element.favorite ? 'yellow' : 'green']">
      {{element.name}}
    </span>
  </div>
</template>

<style >
  .green {
    color: green;
  }
  .yellow {
    color: yellow;
  }
</style>

Answer №2

There is a flaw in your code where the fillcolor method should be executed on each click, but instead, you are calling the changeFav method which only changes the item.fav property without triggering the fillcolor method.

To fix this issue, you need to modify your code as follows:

<v-container fluid>
      <v-row>
        <v-col v-for="(item, index) in items" :key="index">
          <v-btn icon @click="changeFav(item)">
            <v-icon :style="{ color: `${fillcolor(item)}` }">mdi-heart</v-icon>
          </v-btn>
        </v-col>
      </v-row>
    </v-container>
export default {
  ....,
methods: {
    fillcolor(item) {
      return item.fav ? "purple" : "orange";
    },

    changeFav(item) {
      item.fav = true;
      return this.fillcolor(item)
    },
  },
}

================================================================ Alternatively, you can achieve the same result with the following code:

 <template>
  <v-app>
    <v-container fluid>
      <v-row>
        <v-col v-for="(item, index) in items" :key="index">
          <v-btn icon @click="item.fav = !item.fav">
            <v-icon :color="item.fav ? 'purple': 'red'">mdi-heart</v-icon>
          </v-btn>
        </v-col>
      </v-row>
    </v-container>
  </v-app>
</template>

However, the approach you choose depends on how you handle your data. If you are using vuex, then you should consider using mutations. Assuming you have the items and can manage them as shown below:

export default {
  data: () => ({
    items: [
      { name: "t1", fav: false },
      { name: "t2", fav: false },
      { name: "t3", fav: false },
      { name: "t4", fav: false },
      { name: "t5", fav: false },
      { name: "t6", fav: false },
      { name: "t7", fav: false },
    ],
  }),
};

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

Explication of syntax not functioning

Following the instructions provided here but encountering issues, any assistance? <script type="text/javascript" src="sh/src/shCore.js"></script> <script type="text/javascript" src="sh/scripts/shBrushJScript.js"></script> <lin ...

Challenge with adjusting opacity of background when hovering over a box

I've encountered an issue with the background transparency in the following demo. For some reason, it's not working properly. .figure .caption-mask:hover { background: rgba(0, 0, 0, 0.0); } I'm attempting to remove the opacity f ...

Is there a way to circumvent the mouse up event?

I want to create a feature where when a user clicks down, something specific occurs. The sequence of events includes: An action taking place (which is not the focus here). Triggering a mouse up event. Implemented with: angular, html, css. Excludes: jQue ...

How can you style an HTML tag using esc_html in CSS?

I've encountered an issue while editing the woocommerce orders.php template. This template is responsible for displaying the user's placed orders. I have identified several variables that require secure coding, such as $date_created or $view_orde ...

I encountered an issue with displaying API data in V-data-table using axios in Vue.js - unfortunately, the data was not showing up as expected

I am a novice attempting to access an API and display the data in a table using Vue.js and Vuetify. Although I have successfully retrieved the data from the API, I am encountering difficulties displaying it with v-data-table. Below is my code: HTML secti ...

Witness the profound impact unfolding at a deeper level

I need to track changes in an array and log when a value inside it has been updated. Currently, my code only logs items when they are added or removed from the array. I would like to also log when a specific property like item.Circle.position changes. I h ...

Difficulty in displaying JavaScript function output as text

I'm currently developing a program that randomly selects and prints a function from an array list. I am facing difficulties in getting the result to print correctly. Below is the snippet of code: const hiddenElements = document.querySelectorAll( &qu ...

Utilize the "display: flex" property to position an avatar alongside a comment that is wrapped

Looking for a solution similar to the problem presented in this Stack Overflow thread about positioning text next to an image, but specifically when using "display: flex". We are facing an issue where a comment, consisting of an avatar image and accompany ...

Footer disappearing on iPad Safari viewing

I'm currently facing an issue with the footer on a website I'm working on. Everything is working fine except for when the site is viewed on Safari on an iPad. The footer is appearing way above the bottom of the page and after spending an hour try ...

My jQuery carousel seems to be malfunctioning. Check out the issue here on JSFiddle

I found this amazing resource for jQuery carousel functionality: If you'd like to see it in action, check out the JSFiddle demo I created: http://jsfiddle.net/svQpc/ However, I've encountered a small issue with the Horizontal version of the car ...

Is all of the CSS stored in one or multiple files?

Will the number of CSS files on my website impact its performance? I understand the necessity of having a separate file for print styles, but I'm wondering about the other CSS files. Is it better to have all my styles in one file or split them into mu ...

Tips for toggling the visibility of a flexbox-styled popup using jQuery

I am trying to implement a popup on my website and I want to use flexbox styling for it. I have the necessary scss mixins for flexbox properties, however, I encountered an issue. The problem arises when I try to hide the popup using display: none, as the ...

Dividers afloat - expanding current script with multiple additions

I am currently utilizing this website as a hub for showcasing my various web projects. The jsfiddle code provided in response to this particular inquiry is exactly what I need, however, I am unsure of how to have multiple divs moving simultaneously acros ...

Using jQuery to retrieve the location of an element with a specific class

I am working on a slider that adds a class (.current-item) to each active tab and removes it when it's inactive. I am looking to incorporate the LavaLamp effect for the menu, but I am having trouble getting the position of each element with the curren ...

Align Text with Icon Using FontAwesome

Hey, I'm having a bit of trouble with something simple and it's driving me crazy. All I want to do is center the text vertically next to a FontAwesome icon. However, no matter what I try, I just can't seem to get it to work. I've looke ...

The IntersectionObserver doesn't seem to be working on iOS, yet it functions correctly on Android within a Nuxt

My Current Situation Utilizing IntersectionObserver on my feed page to mimic the behavior of TikTok. When scrolling up or down, the next video is displayed and starts playing when in view. When scrolling out of view, the video stops playing. The Issue at ...

The dropdown menu in the navigation bar is not properly lined up with its corresponding menu item

I've been struggling to align my submenu with the navbar, and I suspect there is an issue with the CSS that I can't seem to figure out. CodePEN: https://codepen.io/wowasdi/pen/xxKzdQq Even after trying to adjust the navbar CSS settings by changi ...

What is the best way to make sure the background color of a container stretches across the full width of the screen?

I am currently learning HTML and CSS, and as a practice project, I am working on building a portfolio webpage. In the image provided, there are two containers, and I am facing an issue with the space on the sides when changing the background color. Despite ...

Determine the active state of the router link to correspond with the prop

I am currently tackling a Vue project that involves vue-router with deeply nested routes, such as 2/company/staff/1/timeline. However, I have encountered an issue at the (...) /staff/:id section where all route links are appearing as active regardless of ...

What are some ways to enable text highlighting when it is disabled?

I've encountered an issue with text highlighting in my asp.net web application when using the latest versions of FireFox and Google Chrome. Strangely, pressing CTRL+A also does not work for all input fields. I haven't had the opportunity to test ...