Tips for applying styles with an on-click event in a loop

I have an array of objects (items) that can be incremented with other items, which are displayed by looping through the array.

Take a look at the image here:

https://i.sstatic.net/AXRGQ.png

When I click on an item, I want to highlight it (for example: change its border-top-color), but I'm struggling to target a specific element and apply a style without affecting the entire array. Any suggestions?

This is my template, please note that I am using vuedraggable:

<template #item="{ element }">
          <div
            class="item"
            :key="element"
            @click="
              messageItemTitle(element.title);
              messageItemID(element.id);
              "
          >
            <div class="item-title">
              {{ element.title }}
            </div>
            <div class="item-subType">
              {{ element.type }}
            </div>            
            
          </div>
</template>

The script : None of my previous code has worked, so here's just the data :

data() {
    return {
      dragItems: dragItemsList, //15 items that can be cloned into dropItems 
      dropItems: [],            //Array where I can add the items from dragItems
    };
  },

Answer №1

If you want to conditionally add a class, you can do so using Vue.js:

const app = Vue.createApp({
  data() {
    return {
      items: [{id:1, title: 'aaa', type: 'type1'}, {id:2, title: 'bbb', type: 'type2'}, {id:3, title: 'ccc', type: 'type3'}],
      selected: null
    };
  },
  methods: {
    message(el) {
      this.selected = el.id
    }
  }
})
app.mount('#demo')
.item {
  border: 3px solid transparent;
  border-top-color: black;
}
.selected {
  border-top-color: green;
}
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div v-for="(element, i) in items" :key="i">
    <div
      class="item"
      :class="selected === element.id && 'selected'"
      :key="element"
      @click="message(element)"
    >
      <div class="item-title">
        {{ element.title }}
      </div>
      <div class="item-subType">
        {{ element.type }}
      </div>            
    </div>
  </div>
</div>

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

Which is more efficient in JavaScript: Arrays, Object literals, or JSON for achieving better performance?

I'm facing a tough decision in choosing the most effective option. Currently, I have a simple array set up like this: var array = [ '/index1.html', '/index2.html', '/index3.html' ]; While this array consists ...

What could be causing the data in the data table to remain undeleted unless the page is manually refreshed

I am facing an issue with the delete button functionality. When I press the button, it successfully deletes the row but requires a page refresh to make the deleted row disappear. How can I resolve this problem and ensure that the row is deleted without the ...

Node.js web server operating on port 3000 is running a script

I have developed a Node.js script that extracts data from a database and saves it in a file. Additionally, I have set up a Node.js web server listening on port 3000 using forever to keep it running constantly. However, the script currently lacks a web inte ...

Exploring the application of the PUT method specific to a card ID in vue.js

A dashboard on my interface showcases various cards containing data retrieved from the backend API and stored in an array called notes[]. When I click on a specific card, a pop-up named updatecard should appear based on its id. However, I am facing issues ...

Utilize Sass @extend to incorporate imported CSS files in the build process

In my development setup, I have a global CSS file that houses all of the generic CSS styles. My goal is to extend the classes from this global CSS file in any of my SCSS files. However, when I attempt to do so, I encounter an error stating that the .xyz c ...

adjusting dimensions of swf file within html code

I am trying to insert a small speaker icon from the following url: . However, when the flash is loaded, the dimensions of the swf file exceed those specified in the html tag. How can this issue be resolved? <div style="display: inline;float:center;"& ...

Issue: Unable to open port (GetCommState) : Error code 1 not recognized - Utilizing Nodejs, express, SerialPort

I am currently attempting to establish a connection between a fiscal printer with serial input and nodejs. I am utilizing the SerialPort module, but encountering difficulty in establishing the connection. The console is displaying the following error messa ...

Creating a React component for a button that toggles between 3 different

Looking to create a button with 3 different states that handle click events and send values. The states needed are: Non-favourite Favourite Uber-favourite Attempted using this.state.count + 1 to represent the levels but faced challenges. Unsure if this ...

Is there a way to trigger this floating menu to appear only when certain #divs are in view?

I was looking to create a floating menu and came across a helpful script on here /* Script by: www.jtricks.com * Version: 1.12 (20120823) * Latest version: www.jtricks.com/javascript/navigation/floating.html * * License: * GNU/GPL v2 or later http:// ...

User input can be masked with jQuery to accept two distinct formats

I need help creating an input mask that requires two different values from the user. I want the final input to look like this: [X.XXX$ for X years] Is it possible to achieve this using the jQuery Plugin inputmask? I've attempted with the code snippe ...

When utilizing ES6, my HTML elements do not have event listeners re-attached to them unless I refresh the page

So, I have a task where I am displaying a simple string on the screen. The goal is that when you click on any letter in the string, it should be removed from its current position and added to the end of the string. However, after clicking on a letter and u ...

Slight Misalignment of Elements

I am attempting to align two corners of an element so that they perfectly match the corners of another element. In simpler terms, I am aiming to synchronize the corners of one element with those of another element. Below is the code snippet: ... When y ...

There are no Vue.js updates reflected in Heroku when using Laravel

I've encountered an issue with Heroku (PaaS). I'm in the process of launching my first project using Laravel, and I'm consistently making changes. It's my understanding that every modification made during development needs to be pushed ...

The HTML video controls in Safari take precedence over the window.name attribute

When using Safari 8.0.5, the controls attribute for the video element will change the value of window.name to "webkitendfullscreen". This is significant because I rely on using window.name to store client-side data in Safari's private mode, where loca ...

Dealing with the challenge of managing multiple instances in a setup involving Ajax long polling (comet) and PHP on Lighttpd v1

I am a newcomer to this platform, so I hope to provide all the necessary details about my question. I have been attempting to set up a mechanism for "new message arrived notification" using long polling. Currently, I am triggering the polling request thro ...

How can I transfer data from an API response containing an array of objects to a new array in a Vue.js

How come I am getting NaN instead of "qwe" and "qweqweqwe" when trying to push the first 6 elements from an array of objects to a new array? Imagine the array of objects retrieved from the API is structured like this: 0: {id: 340, name: "qwe", lastname: ...

Dealing with Redis session management in the event of a database disconnection

Having trouble with losing connection to Redis, which is used for sessions in my Express App. var RedisStore = require('connect-redis')(express); sessionStore = new RedisStore(config.db.redis.connection); sessionStore.client.on('error' ...

Changing the size of a div using jQuery

I'm attempting to adjust the size of a div element. You can view my progress in this code fiddle: https://jsfiddle.net/bj3m24ks/31/ Kindly refrain from sharing links to other tutorials as I have already explored them all. I attempted to utilize the $ ...

Dynamic CSS class alteration on scrolling using Vue.js

I am currently in the process of developing a web application using vueJs and bootstrap. I am interested in figuring out how to dynamically change the CSS class of an element based on scrolling behavior. Is there a vue-specific method that can achieve this ...

Using window.location.replace() for redirection after AJAX call succeeds

Attempting to redirect the page after a successful ajax call, the code below is functional: $.ajax( { type: "POST", url: path, data: response1, contentType: "application/json", success: -> window.lo ...