Using dynamic classes within a v-for loop

Edited How can I dynamically assign classes to multiple elements within a v-for loop? Since I cannot utilize a computed property due to the presence of v-for, I attempted using a method by passing the index of the element, but that approach did not yield the desired result.

                    <div v-for="(pet,index) in pets"
                      :key="pet.id"
                      :index="index">
                      <v-row
                class="d-flex justify-center"
              >
                ... (code continues)

When a user selects a button, both the card containing the button and the button itself should have their styles modified to indicate selection. All other cards and buttons should revert to their default styles, emphasizing the selected card among the group.

Answer №1

Is this similar to what you had in mind?

<template>
  <div class="hello">
    {{ selected }}
    <button
      v-for="item in items"
      :key="item"
      @mousedown="selected = true"
      @mouseup="selected = false"
      :class="{ selected: selected, 'not-selected': !selected }"
    >
      {{ item }}
    </button>
  </div>
</template>

<script>
import { ref, reactive } from "vue";
export default {
  name: "HelloWorld",
  setup() {
    const items = reactive(["btn1", "btn2", "btn2"]);
    const selected = ref(false);
    return {
      selected,
      items,
    };
  },
};
</script>

<!-- Make sure to include the "scoped" attribute for CSS styling within this component only -->
<style scoped>
.selected {
  background-color: blue;
}
.not-selected {
  background-color: yellow;
}
</style>

I'm not quite following your objective here

Edit1:

In this case, I suggest creating two components:

  • The "container" component that contains the array of pets and utilizes a v-for loop
  • A "pet" component that displays individual pets

Add a boolean property to each pet indicating if it is selected.

In the "pet" component, assign classes based on this boolean.

Refer to the example provided for adding classes based on booleans.

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

Creating a centered and beautifully styled picture with a specific maximum size using React

I recently completed the development of a new website, which can be viewed at Upon inspection of the website, it is evident that the photo is not centered and appears too large on mobile phones. Despite my efforts to align it using various methods outline ...

Error: XYZ has already been declared in a higher scope in Typescript setInterval

I've come across an interesting issue where I'm creating a handler function and trying to set the current ref to the state's value plus 1: const useTimer = () => { const [seconds, setSeconds] = useState(0); const counterRef = useRef(n ...

Ensure that the search input field is in focus whenever the showSearch state is true

Having difficulty focusing on the input field whenever the showSearch state is true. Utilizing useRef and useEffect for this purpose. When the showSearch flag changes, the useEffect hook is triggered to check if showSearch is true, and if so, it should foc ...

How can I incorporate eventData when using .bind() for the "keydown" event type?

I want to achieve something like this: var keydownHandler = function (ev) { alert(ev.data.test); return false; } $(document).bind('keydown', {test: 'foo'}, keydownHandler); However, the .bind method doesn't seem to be wor ...

JavaScript detecting improper XHTML syntax

Is there an effective method to detect malformed XHTML within a string using JavaScript? Given that my page allows user-generated XHTML (from trusted users) to be inserted into the DOM, I aim to identify unclosed or overly closed tags. If found, I intend ...

Persisting dynamically generated table information into a multidimensional array

I've created a dynamic table and now I'm trying to extract the data from it and store it in a multidimensional array. However, I keep encountering an exception/error that says "Cannot set property of 0 to undefined". https://i.sstatic.net/W8B9j.p ...

Encountering the error message "Unexpected token. Did you mean {'>'} or &gt;?" when trying to use an arrow function in React

I recently started learning React and Javascript. I encountered an error message that said: "Unexpected token. Did you mean {'>'} or &gt;?", specifically in relation to the "=>" part of the code below. This issue arose while I was worki ...

Is there a way to transform these into five columns within a single row using the Material-UI Grid system?

I'm trying to align 5 columns in one row, but I'm struggling to achieve the desired layout. Here is what I currently have: https://i.stack.imgur.com/d3z3n.png Any tips on how to make all columns appear in a single row? You can also view my att ...

Challenges with managing VueJS methods and understanding the component lifecycle

I'm facing an issue with my code. The function retrieveTutorials() is not transferring the information to baseDeDatosVias as expected. I've attempted to change the function to a different lifecycle, but it hasn't resolved the problem. The so ...

unable to use redirect feature for specific URLs with nodejs module

I have been using the request nodejs module to retrieve HTML content from websites. However, I have encountered issues with certain redirection websites, as shown below: var request = require('request'); var options = { url: "http://www.amw ...

What is the process for retrieving an object from a node.js server using JSON.stringify() in a JavaScript file?

Looking to organize my code, I want to separate the JavaScript from my page and link it through a file instead of having it embedded within script tags. The issue arises when I receive a "SyntaxError: expected expression, got '<' " in Firefox ...

Create a table within the B-Col element that automatically adjusts its size to match the column width using Vue-Bootstrap

Within my Vue component, I have the following code snippet: <b-modal ...> <b-row> <b-col sm="12"> <table > <tr v-for=... :key="key"> <td><strong>{{ key }}: </str ...

Is it possible to utilize various return values generated by a regex?

Working on a project where I am utilizing regex to extract links from a Google Calendar XML feed. The links appear in the following format: <a href="http://www.drsketchysdublin.com/event-registration/?ee=11">http://www.drsketchysdublin.com/event-reg ...

Challenge with Vite, React, and MSW Integration

Having some trouble setting up MSW in a React application. It's unusual for me to come across issues like this. I've configured an environment variable VITE_MOCK set to true when running the yarn start:mock command. This should enable API mocking ...

Can someone please explain how to prevent Prettier from automatically inserting a new line at the end of my JavaScript file in VS Code?

After installing Prettier and configuring it to format on save, I encountered an issue while running Firebase deploy: 172:6 error Newline not allowed at end of file eol-last I noticed that Prettier is adding a new line at the end when formatting ...

Difficulty establishing a connection between the front end and backend Web API

I am in the process of developing a full stack application and encountering a CORS error when trying to connect to my backend. Despite allowing the link in my Web API, the issue persists. Below is an excerpt from my Web API program.cs: using Api.Data; na ...

Why won't my AngularJS Google Maps marker trigger any events?

My issue is with the marker event not working on a UI Google Map. I am using this link. Here is my view setup: <ui-gmap-markers models="mapResult" fit="true" idkey="mapResult.id" coords="'form_geo'" click="'onclick'" events="mapRe ...

Making an Ajax request with JSON is yielding unexpected variables that cannot be modified or removed

Attempting to make an AJAX call using a script: $.ajax({ url: pageURL, data: loadData, type: 'POST', cache: false, dataType: 'json', success: function (data) { //if the call was successful console.log(su ...

What is the best method to dynamically assign a class to a TD element in a data table when adding

I am looking to apply a class to the td element when receiving data from an ajax call Here is the default HTML code snippet <tr> <td>@fisrt.System_Code.Code</td> <td>@fisrt.System_Code. ...

Is there a way to adjust the size of text to perfectly fit within a fixed size div?

I find this scenario quite common, but I haven't come across any solutions for it: Let's say there is a fixed-width div that displays dynamically changing numbers. How can we adjust the font size so that larger numbers fit well within the fixed ...