Change the background color of a particular row in a table using Vue.js to be red

I am having an issue with a regular table - when I click on a specific row, I want only that row to turn red.

Below is the code snippet that I have attempted:

<tr role="row" v-for="(proxy, key) in this.ProxiesList" @click.prevent="this.BackGroundRed = !this.BackGroundRed" v-bind:style="[this.BackGroundRed ? 'background-color:red' : '']">

<td class="sorting_1"><a href="#"><span class="inv-number">{{ key + 1 }}</span></a></td>
<td>
<div class="d-flex">
<div class="usr-img-frame mr-2 rounded-circle">
<img alt="avatar" class="img-fluid rounded-circle" src="/img/logo-mini.png">
</div>
<p class="align-self-center mb-0 user-name"> {{ proxy.ProxyIP }} </p>
</div>
</td>
</tr>

VUEJS

data() {
    return {
        BackGroundRed: false
    }
},

However, the issue persists as clicking on a row turns all rows red!

Answer №1

If you're looking to implement a functionality like the one described below in your project, you can use the code snippet provided (avoid using this in template):

new Vue({
  el: '#demo',
  data() {
    return {
      backgroundRed: null,
      ProxiesList: [{id:1, ProxyIP:1}, {id:2, ProxyIP:2}, {id:3, ProxyIP:3}, {id:4, ProxyIP:4}]
    }
  },
  methods: {
    setBg(id) {
      this.backgroundRed = id
    }
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <table>
    <tr role="row" v-for="(proxy, key) in ProxiesList" @click="setBg(key)" :style="backgroundRed === key ? 'background-color:red' : ''">
      <td class="sorting_1"><a href="#"><span class="inv-number">{{ key + 1 }}</span></a></td>
      <td>
        <div class="d-flex">
          <div class="usr-img-frame mr-2 rounded-circle">
            <img alt="avatar" class="img-fluid rounded-circle" src="/img/logo-mini.png">
          </div>
          <p class="align-self-center mb-0 user-name"> {{ proxy.ProxyIP }} </p>
        </div>
      </td>
    </tr>
  </table>
</div>

Answer №2

If the variable BackGroundRed is set to true, all the <tr> elements in your code will have a red background color.

To address this issue, consider creating an array to store selected rows and add the row identifier to it upon selection. Then, you can easily check if the current row identifier is in the array of selected rows and apply the red background accordingly.

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

Static Header - Halts Animation on Downward Scroll, Resumes when Scrolling Ceases

I've implemented a fixed menu on my website. Everything seems to be working fine, but here's the issue: When I scroll down and the fixed menu starts animating, if I continue scrolling quickly, the animation pauses. It only continues when I stop ...

What is the best way to utilize Link for navigation in React with Material UI?

const pages = ['home', 'menu', 'reservation']; <Box sx={{ flexGrow: 1, display: { xs: 'none', md: 'flex' } }}> {pages.map((page) => ( <Link component={Link} to='/'>Home</L ...

troubleshooting Axios errors in React applications

User/Project.js: import React, { useState, useEffect } from "react"; import Axios from "axios"; const Project = () => { const [projectName, setprojectName] = useState(""); const [projectDescription, setprojectDescriptio ...

Prevent secret select fields from being submitted within a form

In my interface, there are a couple of dropdowns where a user can select the first option and based on that selection, a new dropdown will appear. Currently, when posting the form, all the select dropdown values are included in the post data, even the hid ...

What is the best location in Backbone.js to store code unrelated to the view, such as ads and analytics?

In my development of a backbone.js application, I have come to understand the role of each backbone "class" as follows: Model: This represents the data object, where the outcome of an API call is stored. Collection: An organized group of models, for exam ...

Easy methods to navigate between screens without using React Router libraries

After experimenting with two different methods to switch between screens in a simple application (up to 3 modes/screens), I am still in the learning phase and mainly focusing on practicing with useState and possibly useEffect for certain scenarios. I&apos ...

Is there a way to automatically refresh a page as soon as it is accessed?

My goal is to create a page refresh effect (similar to pressing Command+R on Mac OS) when navigating to a certain page. For instance: Currently, when I navigate from "abc.com/login" to "abc.com/dashboard" after successfully logging in, the transition occ ...

The window resizing function continues on an endless loop

I could really use some assistance in pinpointing the issue at hand! My script is set up to display a banner at the top of a page only if the window width is 600px or less and the scroll position is within 34px from the top. It hides the banner when the u ...

Update individual component based on selected value

I am working on a blogs page that consists of two main components: filter and card <template> <div> <div v-if='$apollo.loading'>Fetching data...</div> <div v-else> <FilterComponent :categorie ...

The message "Error: Unknown custom element: <router-view> - have you properly registered the component?" is prompting for a solution

Even though the name is correctly capitalized in all my component instances, I am still encountering an error. After researching similar issues online, it appears that the problem usually revolves around naming discrepancies. However, I have double-checked ...

efforts to activate a "click" with the enter key are unsuccessful

I'm attempting to enhance user experience on my site by triggering the onclick event of a button when the enter key is pressed. I've tried various methods below, but all seem to have the same issue. Here is my HTML (using Pug): input#userIntere ...

Using Javascript, access the 'second child' element by referencing the 'first child' element within a shared 'parent element'

// Retrieve the child_2 element using core javascript let parent = document.querySelector('.child_1').closest('.parent'); let child_2 = parent.querySelector('.child_2'); How can I achieve the same functionality as the jQuery ...

Avoid interrupting the code execution until it has finished completely

Let's discuss a common scenario: $('button').on('click',function(){ // Performing AJAX requests (which may take some time); }); If the user clicks the button multiple times, numerous ajax requests can be triggered. To prev ...

Prevent CSS3 columns from reverting back to their original state after being rendered

Utilizing css3 columns, I have created a layout with an unordered list displayed in 3 columns. Each list item contains another list that can be toggled to show or hide by clicking on the title using jQuery. The structure of the html is as follows (with ex ...

Navigating a Multi-Page Website with Sleek Scrolling

I've been searching for a solution everywhere but haven't had any luck. I'm trying to implement a smooth scroll effect that works seamlessly across multiple pages. For instance, the smooth scroll effect is present on the homepage with naviga ...

The final output message from the NPM package is displayed right at the conclusion

Is there a way to add a log message at the end of the npm install process? To enable CLI tab autocompletion run: mypackage completion >> ~/.profile <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d5a5a7bab2a7b0a6 ...

Interpolating backticks in Javascript allows for constructing a URL containing empty spaces

When utilizing string interpolation with backticks to construct a URL that sends data to a django endpoint, the resulting URL contains unnecessary whitespace and a new line. The problematic JavaScript code is as follows: (function (window, document, unde ...

Moving the legend around in vue-chartJS

As someone just starting out with Vue-ChartJs, I've become quite intrigued by this: https://i.sstatic.net/j1S0z.png I'm wondering how to move the legend to the bottom of the graph. Can anyone help me with that? ...

Dealing with errors effectively in AngularJS $http requests

What is the best approach for handling connection errors in Angular? When using the $http POST service: dossierService.getDossier(uid) .then(function (result) { vm.dossier = result.dossier; }, function (error) { handleErro ...

What is the best way to trigger a javascript modal to open automatically after a specific duration

Let's take an instance where my modal has the ID #modal1. It usually appears through a button-based action. ...