Using v-bind:class to assign an object value

I have a Vue component that displays an image grid. I want users to be able to select an image by clicking on it. When an image is selected, its style should change, and if clicked again, it should return to its unselected state.

I am trying to bind the 'image-box-selected' class to a specific image, but I am facing some challenges. I cannot simply read a data attribute because that would cause all images to be selected simultaneously. Instead, I am using a selectedImages object as a dictionary for each imageId, where selectedImages['qhasdk'] will map to either false or true.

The problem I am encountering is that even though the selectedImages object is being generated and updated correctly, the 'image-box-selected' class never actually appears, even when the relevant key in selectedImages has been changed to true.

Vue.component('images-grid', {
    props: ['env', 'images'],
    data: function () {
    return {
      selectedImages: {}
    }
  },
    methods: {
        getSourceUrl: function (imageId) {
            return getRootUrl() + '/image/' + this.env + '/' + imageId
        },
        updateSelectedImages: function (imageId) {
            /* First we check we populated selectedImages with the IDs. */
            if (Object.keys(this.selectedImages).length === 0) {
                for (var i = 0; i < this.images.length; i++) {
                    this.selectedImages[this.images[i].id] = false;
                }
            }
            this.selectedImages[imageId] = !this.selectedImages[imageId];
        }
    },
  template: `
        <div>
            <img
                v-for="image in images"
                v-bind:id="image.id"
                class="image-box image-box-selectable"
                v-bind:class="{'image-box-selected': selectedImages[image.id]}"
                v-bind:src="getSourceUrl(image.id)"
                v-on:click="updateSelectedImages(image.id)">
        </div>
    `
})

Answer №1

Avoid relying on selectedImages[image.id] for retrieving the value, especially when selectedImages is an object. It is recommended to access the value in the following manner:

selectedImages->image.id

If this approach seems too intricate, consider utilizing "methods" to fetch the value instead.

Answer №2

My preference lies in utilizing immutable methods, where I assign the value of this.selectedImages to a new object:

updateSelectedImages: function (imageId) {
  /* First we ensure that selectedImages is populated with the IDs. */
  if (Object.keys(this.selectedImages).length === 0) {
      for (var i = 0; i < this.images.length; i++) {
          this.selectedImages[this.images[i].id] = false;
      }
  }
  this.selectedImages[imageId] = !this.selectedImages[imageId];
  this.selectedImages = [...this.selectedImages] // ES6
  // this.selectedImages = JSON.parse(JSON.stringify(this.selectedImages)) // ES5
}

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

Placing the jQuery/javascript source pages right before the closing body tag

Multiple plugin instructions recommend placing the javascript/jQuery source right before the closing body tag. I wondered why this advice is given, but couldn't find a clear explanation for it. In my experience, placing the src file anywhere in the s ...

How can I send data in JSON format to a JavaScript AJAX request?

I've created a method that looks like this: public String getUTResult() throws IOException { BuildResultParser bp = new BuildResultParser(); BuildResultBean b = bp.getreadFile("C:\\bc.txt"); String str = b.getuTresult(); ...

require an array that contains an embedded object

When making a post request, I need to include an array with an object inside. I have observed that adding new properties inside an object works fine. However, when attempting to add properties while the object is inside an array, it does ...

Tips on concealing all classes except one through touch swiping

If you have a website with a single large article divided into multiple sections categorized as Title, Book1, Book2, & Book3, and you want to implement a swipe functionality where only one section is displayed at a time, you may encounter some issues. ...

Adjust the appearance of an element based on user selection from a dropdown menu under certain circumstances

I am working on creating a dropdown menu using a JavaScript array. My goal is to display a specific span element when certain options are selected. For instance, I want the span to be shown only when options "a" and "c" are selected, but not when option " ...

When incorporating Typescript into HTML, the text does not appear in bold as expected

Issue with bold functionality in Typescript Hey there, I am currently involved in an Angular project and I came across a problem with a function in a Typescript file that is supposed to bold a specific segment of text formatText() { ......... ...

What is the best way to choose an HTML element in React?

Is there a way in React to change the theme value based on localStorage and set it to either light or dark mode? https://i.sstatic.net/Iecsj.jpg I am familiar with using Ref hooks in components, but how can I access a DOM element in the index.html file? ...

Ways to incorporate a unique debounce technique where the function is only executed every nth time

const _debounce = (num, fn) => { //implementation goes here } const originalFunction = () => { console.log('fired') } const _callFunc = () => _debounce(2, originalFunction) _callFunc() //The originalFunction does not run _callFun ...

Unable to switch checkbox state is not working in Material UI React

I am experiencing an issue with the Material UI checkbox component. Although I am able to toggle the state onCheck in the console, the check mark does not actually toggle in the UI. What could be causing this discrepancy? class CheckboxInteractivity exten ...

How can we store data coming from PHP using AJAX and update the color of a div whenever new data is inserted?

Hey there, I'm currently working on a project where I need to save values and display them using Ajax after inserting them into a MySQL table using PHP. However, I'm having trouble with the alert function not working as expected. Let me share my ...

Retrieve childNodes of the Select All input using jQuery from the container node with the class name "container"

I am trying to retrieve the text value of all the childNodes within the container of the corresponding input when the Select All checkbox is checked. Currently, my code captures the text inside each input label. However, it only logs the label (e.g. &apos ...

Activate the date-picker view when the custom button is clicked

Utilizing this library for date-picker functionality has been quite beneficial. I am currently working on a feature that involves opening the date-picker upon clicking a custom button. The default input is functioning properly. <input name="pickerFromD ...

Should I use graphite or make multiple AJAX calls for querying data?

I am currently exploring the potential advantages of using Graphite. My web application receives data through JavaScript Ajax calls and visualizes it using Highcharts. To generate each graph, Python runs 20 different queries on my SQL database. The ...

Tips for creating a static background when displaying a modal popup in AngularJS

Incorporating a modal popup to modify a row within a grid view has been my recent task. Leveraging the row.getProperty() function, I successfully extracted the row values within the modal. However, an inconvenience emerged when attempting to edit a value ...

What exactly does the statement if(item.some((item) => !item.available) represent in typescript?

Can you explain the meaning of if(item.some((item) => !item.available))? While looking at some code randomly, I came across this snippet: if(item.some((item) => !item.available){ } I'm curious about what it signifies. Can you elaborate on it? ...

Prevent the use of exponential notation with double numbers in GWT

Is there a way to remove the exponent from a double on the client side in GWT? public double evaluate(final double leftOperand, final double rightOperand) { Double rtnValue = new Double(leftOperand * rightOperand); //Need code to remove expone ...

Is there a way to identify the specific button that was clicked within an Angular Material dialog?

import {Component, Inject} from '@angular/core'; import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material'; /** * @title Dialog Overview Example with Angular Material */ @Component({ selector: 'dialog-overview-ex ...

Is there a way to integrate the javascript and jQuery functions in order to conceal a button?

I recently acquired the File Upload script known as Simple Photo Manager and I am looking to incorporate jQuery functions with the existing JS code in the script. My main goal is to make the Delete button disappear once it has been clicked. However, I am ...

The issue of Rails time lagging by a day persists upon deployment on my server

When a user clicks on a day in my calendar, I pass a JavaScript time variable to my Rails controller using Ajax. Everything works perfectly when I test it locally, but once deployed on the server, the date appears to be one day behind the actual day click ...

What changes can I make to my method in order to utilize async/await?

Within my React application, I have implemented a post request to the server using axios: onSubmit = async (results) => { try { const response = await axios.post("http://localhost:8080/simulate/", results); this.setState({results: ...