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>

https://i.sstatic.net/s2u5x.jpg

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

The performance of dom-repeat may be impacted when dealing with sizable objects, such as those containing base64 encoded images

Currently, I am encountering an issue while generating a dom-repeat using a list of objects. Each object in the list has an imgUrl key containing a large base64 encoded image. However, when I generate the dom-repeat in this manner, each item appears undef ...

AngularJS allows for versatile filtering of objects and arrays using checkboxes

I am looking to implement a filter functionality similar to the fiddle mentioned in the first comment below. However, I do not want to capture the checkboxes category from ng-repeat. Instead, I only want to input the checkboxes' value and receive the ...

Track the number of times a button is clicked to generate a prominent "Main Event" section

Currently, I am working on a Tourism website that showcases numerous tours. Utilizing WordPress, I have established a custom post type titled Tours. Each tour is equipped with a Book Now button, which has been generated as a custom meta box. This button d ...

Transferring data between Javascript and PHP with AJAX and JQuery

I'm currently working on a basic web page that involves sending data from an HTML page to a PHP script and receiving some data back. My approach involves using AJAX, but for some reason, the PHP script doesn't seem to execute at all. Here's ...

Integrating SignalR with Vue and Vuex for Real-Time Communication

I have been attempting to establish a connection between a SignalR hub and a Vue component, but so far I have not been successful. I have searched extensively for solutions by googling "vue with signalr" and reading through numerous links, even going as fa ...

What is the primary function for Express.js and Node.js 10 in Google Cloud Functions?

My Node JS version is 10 Express JS version: 4.16.1 I understand that for Node JS 8, the entry point should be "app" The generated code (from `npm install -g express-generator) www #!/usr/bin/env node /** * Module dependencies. */ var app = require( ...

What is the best way to retrieve the content from the MongoDB Document in my GET request?

I encountered an issue while attempting to access the Question field within the JSON document body stored in a MongoDB database. Upon executing the GET request, the result displayed as follows: { "_readableState": { "objectMode": true, "highWaterM ...

Guide on adding a new member to Mailchimp through node.js and express

Hello, I've been delving into working with APIs, particularly the mail-chimp API. However, I've encountered a problem that has me stuck: const express=require("express"); const bodyparser=require("body-parser"); const request=require("request" ...

Step-by-step guide to creating a pop-up div that appears on hover and remains visible when clicked

I'm trying to figure out how to make a popup appear when the mouse hovers over it and then stay visible when clicked on. The issue I'm facing is that currently, the popup disappears when the mouse moves away from it. How can I modify the code so ...

I want to use React Bootstrap and Next.js to retrieve the text from a textbox in a React Component and then send it back to my Index.js file. How can I accomplish this task?

I need some assistance. Currently, I am facing a challenge. I am trying to retrieve data from one of my React Components named ParameterList. This component contains a React-Bootstrap Form.Control element for numerical input. My goal is to take the value ...

get an array of JSON data from a VueJS fetch or axios.get request

I can't seem to figure out this issue. The code I have below is giving me some trouble. When I try to run it, I keep getting the following error message: Access to XMLHttpRequest at 'URL' from origin 'http://localhost:8000' has b ...

The command "npm run build:css " is not functioning properly, but when I execute the script independently, it works fine

Recently, while working on a program using npm script on my Mac system, I encountered some issues. Despite having installed node-sass globally, running "npm run build:css" did not work as expected. The content of my package.json file can be viewed here. Th ...

Having trouble with looping through subarrays using Javascript and JSON

I am attempting to iterate through a JSON object using Javascript (jQuery). Within the main JSON object, each object in the array contains embedded arrays of tags. My goal is to loop through all the files in the main object and simultaneously iterate thro ...

"Utilize an HTML input to query and retrieve data stored in a

Seeking to retrieve data from my MySQL database and display it on the website securely. List of existing files: /includes db_connect.php functions.php getdata.php logout.php process_login.php psl-config.php register.inc.php /j ...

Run the function once the page has completed downloading and bootstrapping

After experimenting with $evalAsync and $viewContentLoaded, I've found that they only trigger after Angular has completed populating the template. My goal is to determine, from within a directive: Is the template fully replaced by Angular? Have all ...

What is the method for arranging objects in AngularJS using a custom sorting sequence?

I would like to display an array of object's properties in a custom sorted order. Here is the initial array: $scope.weekDays = [ { "day" : "TUESDAY", "count": 10 }, { ...

Ensure that the children elements can be resized without exceeding the boundaries

My goal is to ensure that the resizable elements stay within their parent element. What I tried: I have set the minHeight : property and while resizing, I am using Math.max to limit the height to 30px. Expected Result: All resizable child elements sh ...

Ways to retrieve "this" while utilizing a service for handling HTTP response errors

I have a basic notification system in place: @Injectable({ providedIn: 'root', }) export class NotificationService { constructor(private snackBar: MatSnackBar) {} public showNotification(message: string, style: string = 'success' ...

Modifying tags or categories of a post using a sidebar plugin in WordPress Gutenberg

I am currently working on integrating the functionality to add or delete a post's tag or category using a WordPress Gutenberg sidebar plugin built with React and JavaScript. Despite the lack of detailed resources on how to implement this particular us ...

NextJS does not support the rendering of the map function

Currently, I am getting acquainted with NextJS by creating a basic blog. I have successfully passed the data through props and can see it logged in the console within the map function. However, I am facing an issue where the HTML content does not display i ...