I'm attempting to create a button that changes to a bold red color when the condition is met

I am currently working on developing web applications using the Pixabay API. My goal is to allow users to mark an image as a favorite and have the heart icon change color to red accordingly. However, I seem to be facing issues with this functionality.

To achieve this, I am utilizing the makeFav() method to add another boolean property called liked to the existing data.

new Vue({
    el: '#app',
    vuetify: new Vuetify(),
    data: {
      api: 'https://pixabay.com/api/?key=XXXXXXXXXXXXXX',
      images: null, 
    },
    mounted() {
      this.getImages()
    },
    methods:{
    getImages: function(){
      if(localStorage.images){
        this.images = JSON.parse(localStorage.images)
        console.log("Local Image")
      }
      else{
        axios.get(this.api)
        .then(response => (
          this.images = response.data.hits,
          localStorage.images = JSON.stringify(this.images),
          console.log("API Image")
          ))
        .catch(error => (console.log(error)))
      }
    },
    makeFav: function(i){
      this.images[i].liked = !this.images[i].liked
    },
    }
    
})

Within the HTML structure, I am implementing Vuetify cards and checking the color property for the heart icon but encountering difficulties in getting it to work properly.

<v-col md="3" sm="6" v-for="(image, i) in images" :key="image.id"> 
  <v-card> 
     <v-img :src="image.previewURL"> 
     </v-img> 
     <v-card-actions> 
     <v-spacer></v-spacer> 
     <v-btn icon  @click="makeFav(i)"> 
         <v-icon :color="image.liked ? 'red' : ''">mdi-heart</v-icon> 
         {{image.likes}} 
     </v-btn> 
     <v-btn icon @click="downloadWithAxios(image.largeImageURL)"> 
         <v-icon>mdi-download</v-icon> 
     </v-btn> 
    </v-card-actions> 
  </v-card> 
</v-col>

Answer №1

When it comes to reactivity for arrays, Vuejs has its limitations. You can refer to the official documentation for more details: https://v2.vuejs.org/v2/guide/reactivity.html#For-Arrays

Some changes made to an array that Vue cannot detect include:

  • Directly setting an item with the index, for example: vm.items[indexOfItem] = newValue
  • Modifying the length of the array, such as: vm.items.length = newLength

I have identified 2 solutions to address this issue :

First solution - using Vue.set: https://jsfiddle.net/dp6g3qjn/

makeFav: function(i){
  Vue.set(this.images, i, { ...this.images[i], liked: !this.images[i].liked })
}

Second solution - leveraging key: https://jsfiddle.net/2cz0qfye/

<v-col md="3" sm="6" v-for="(image, i) in images" :key="key(image)">
key ({ id, liked}) {
  return `${id}_${liked}`
}

It is worth noting that I personally prefer the first solution as it avoids unnecessary rendering of the object.

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

Error message: "An issue occurred: Unable to access undefined properties (specifically, borderRadius) in MUI react."

I recently created a navigation bar with an integrated search bar component. The styling for my search component was done using MUI styled from @emotion/styled in MUI library, where I applied a borderRadius: theme.shape.borderRadius. However, I encountere ...

Ways to display notifications when the user is not actively browsing the website?

How can websites display notifications even when the user is not actively on the site? Take Facebook messenger, for instance. Even with the page closed, notifications still pop up. The same goes for Twitter, which also sends push notifications. I ...

Graph is vanishing while linked

A unique HTML canvas is included in a standalone file called dashboard.html. To display the dashboard on the main homepage (home.html), we utilize ng-view nested within an ng-if directive. Oddly, clicking on the hyperlink "#" from the home page causes th ...

Error message indicating that the function is not defined within a custom class method

I successfully transformed an array of type A into an object with instances of the Person class. However, I'm facing an issue where I can't invoke methods of the Person class using the transformed array. Despite all console.log checks showing tha ...

Calling Array.prototype.slice results in an array with no elements

As a beginner in Javascript, I am looking to save JSON request data to a sub document in a MongoDB database. My current approach involves converting the JSON request into an array and then utilizing the $push method to pass the array to the sub document. H ...

Receiving a blank array from the firestore database

I have written a code for the LeftBar Component where I am trying to retrieve data stored in the "contacts" document in Firebase. However, I am getting an empty array and I'm not sure why this is happening. Additionally, I would like to know how to ac ...

Is there a way to selectively display items that are grouped with children only?

I am currently experimenting with Vuetify and exploring the usage of v-list-group. I am curious to know if there is a way to prevent the grouping behavior for items that do not have any children? <template> <v-layout fill-height> ...

I am experiencing an issue where the tooltip does not appear when I click the icon. What adjustments can be made to the code to ensure that the tooltip

I have created a feature to copy abbreviation definitions when the clipboard icon is clicked. A tooltip displaying 'Copied' should appear after clicking the icon, but for some reason, it's not visible. Here's the code: $(document).re ...

Exploring the use of callbacks in React closures

After diving into a React related article, I delved deeper into discussions about closures and callbacks, checking out explanations on these topics from Stack Overflow threads like here, here, and here. The React article presented an example involving thr ...

Displaying adornments in a vertical arrangement within a TextField using Material UI

Is there a way to display adornments vertically in a Material UI Textfield? I've been trying but it always shows up horizontally. Snippet: <TextField variant="filled" fullWidth multiline rowsMax={7} onFocus={() => h ...

Kendo's data-bind onclick feature functions properly on web browsers but fails to work on mobile devices

As a newcomer to Kendo and JavaScript, I may be missing something obvious... In one of my list entries, I have a simple call like this: <li style="margin: 0.5em 0 0.5em 0"> <a href="#transaction-details" data-bind="click: onB ...

Encountering a 'Cannot Get /' Error while attempting to reach the /about pathway

I attempted to create a new route for my educational website, and it works when the route is set as '/', but when I try to link to the 'about' page, it displays an error saying 'Cannot Get /about' Here is the code from app.js ...

The script fails to start using npm start, however, it runs smoothly when using node server.js

For a while now, I've been facing an issue that I just can't seem to resolve. When I navigate to my project's src folder and execute `node server.js`, everything functions as expected. I can access the application at http://localhost:3000/cl ...

Implementing a PayPal Payment Button in Vuejs3 using the Composition API setup function

Attempting to integrate PayPal buttons into my Vuejs3 project using the Composition API (setup), I encountered errors. When attempting integration without using setup, everything works perfectly fine. Below is the working script: <script> ...

Unable to locate module: Issue arises because 'vue-csv-import' cannot be resolved

Currently, I am in the process of importing vue-csv-import for vue 2. This was done by executing the following command: npm install [email protected] The package.json file has been updated with the following details: "dependencies": { &q ...

Bringing in the component's individual module

I encountered the error message in my Angular application - Can't bind to 'formGroup' since it isn't a known property of 'form' - and managed to resolve it by including the import import { AddEditModule } from './add.edit ...

Intercept Axios Responses - Retrieving API Responses for HTTP Statuses that are not in the 200 range

I've set up a custom Axios instance with interceptors for handling responses. As per the Axios documentation, the success interceptor is triggered for 2xx statuses while the error interceptor handles any other status codes. My goal is to show an error ...

The function error is currently in a waiting state as it already includes an

I encountered a particular issue that states: "await is only valid in async function." Here is the code snippet where the error occurs: async function solve(){ var requestUrl = "url"; $.ajax({url: "requestUrl", succes ...

An observer is handed to me when I receive an array as a parameter

How can I use an array as a parameter instead of just receiving an observer? When trying to utilize the array, all I get is an observer. The data appears correctly when using console.log in the function that fetches information from the DB. Despite attem ...

Issue with emitting using vuex and vue-socket.io-extended

For practice, I developed a chat app using vue-cli. To facilitate Socket.io connections on the client side, I utilized vue-socket.io-extended as the plugin. In order to connect to the socket within any components, I setup an emit call in vuex store: acti ...