Is it possible to utilize a computed property for dynamically styling a table row based on certain conditions?

I have a table of users that I am currently rendering, and my goal is to highlight the entire row only for the current user.

My initial thought was to use a computed property to achieve this, but I seem to be facing some difficulties in making it work.

In the code snippet below, I left a comment outlining my approach, but unfortunately, it's not producing the desired output. Specifically, I want the row to be highlighted in pink only for the user 'nathan'.

new Vue({
  el: '#app',
  data: {
    currentUser: 'nathan',
    users: [{
        name: "nathan",
        email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8c6c9dcc0c9c6e8cfc5c9c1c486cbc7c5">[email protected]</a>"
      },
      {
        name: "sally",
        email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ff8c9e939386bf98929e9693d19c9092">[email protected]</a>"
      },
      {
        name: "joe",
        email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ee4e1ebcee9e3efe7e2a0ede1e3">[email protected]</a>"
      }
    ],
  },
  computed: {
    styles: function(user) {
      let height = 100

      // something like this?
      // if(user === currentUser)
      if (user) {
        return {
          'background-color': 'pink'
        }
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <table>
    <tr v-for="user in users">
      <td v-bind:style="styles">{{ user.name }}</td>
      <td v-bind:style="styles">{{ user.email }}</td>
    </tr>
  </table>
</div>

Answer №1

The computed property cannot receive parameters, so the user parameter will not be populated.

If you want to apply a specific class based on a condition, you can create a class and assign it to the row accordingly.

new Vue({
  el: '#app',
  data: {
    currentUser: 'nathan',
    users: [{
        name: "nathan",
        email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87e9e6f3efe6e9c7e0eae6eeeba9e4e8ea">[email protected]</a>"
      },
      {
        name: "sally",
        email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed9e8c818194ad8a808c84c38e8280">[email protected]</a>"
      },
      {
        name: "joe",
        email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bad0d5dffaddd7dbd3d694d9d5d7">[email protected]</a>"
      }
    ],
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <table>
    <tr v-for="user in users" :class="{'current-user' : user.name === currentUser}">
      <td>{{ user.name }}</td>
      <td>{{ user.email }}</td>
    </tr>
  </table>
</div>

<style>
  tr.current-user {
    background-color: pink;
  }
</style>

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

Implementing long-lasting login functionality in React using JSON Web Tokens

Currently, I have developed an application using React client/Express API with functioning Authentication. Users are able to register and login successfully. My next step is to implement persistent login using JWT tokens so that when a user accesses the U ...

Vue.js: EventBus.$on is not properly transmitting the received value

I recently started working with Vue and am currently exploring the best way to organize my event bus. In my project, I have a main layout view (Main.vue) that includes a router view where I pass emitted information from a child component like this: <te ...

Nuxt 3: Creating a Lifestyle Blog with Challenges in Loading Dynamic Content

Working on my Nuxt website, I have successfully created the homepage and blog page. However, when navigating to a specific blog post, the page is supposed to fetch the data using async from the store by passing the slug but sometimes an error occurs where ...

User authentication using .pre save process

I have an API that accepts users posted as JSON data. I want to validate specific fields only if they exist within the JSON object. For example, a user object could contain: { "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...

What is the right way to send a success response from Express JS to Backbone when logging out a user?

I'm currently learning how to work with Express JS and Backbone. On the server side using Express.js, I have this code snippet for logging out a user: app.get('/logout', function(req, res) { req.logout(); res.send('How can I ...

What is the process for retrieving information from my Google Analytics account to incorporate into my website?

Imagine being the proud owner of Your website is equipped with a Google Analytics script that diligently gathers data about your valuable visitors. Now, you have a desire to set up a page views counter. How can you extract data from your own account? ...

Unable to utilize ES6 syntax for injecting a service

I am encountering some issues while trying to implement a service into a controller using ES6 syntax. CategoriesService.js export default class CategoriesService { constructor() { this.getCategories = function ($q) { var deferred ...

vuejs props become null upon page refresh

MyComponent.vue template: <ResponsiveNavigation :nav-links="navLinks" /> script data: () => ({ navLinks: [] }), created: function() { this.getSocialMediaLinks(); }, methods: { getSocialMediaLinks() { var self = this; ...

The element's position remains unchanged after the .click re-event in the function

Welcome to my first attempt at using jQuery! Please bear with me as I navigate through this learning process. Here's the challenge: I have a series of elements in my HTML. <div class="garden"> <div class="point left">&#9668;</d ...

What is the significance of "new" being omitted in the upcoming jQuery script?

After diving into the JQuery documentation, I discovered that it is possible to create the event object like this: //Instantiate a new jQuery.Event object without using the "new" keyword. var e = jQuery.Event( "click" ); I find it puzzling why we don&apo ...

Avoid reloading the page in PHP when the browser back button is clicked

I've built an HTML form where the values are passed to a second page using POST method. On the second page, I have an edit button that, when clicked, redirects back to the HTML form page with the user's typed values. However, my dilemma is figuri ...

Tips for troubleshooting Node.js React Express applications

Having a background in traditional programming, I am used to putting breakpoints in code and having the debugger take me directly to the problematic section when executed. However, as I delve into web app development, it seems that debugging is limited to ...

Can you explain the distinction between these two Redux reducer scenarios?

While looking at someone else's code for a reducer, I noticed this snippet: export default function reducer(state, action) { switch(action.type) { case 'ADD_TODO': Object.assign({}, state, { ...

Is it possible to insert clickable links within the content of a Twilio text message?

Currently, I am utilizing Twilio and Express to send programmable SMSs to the users of my web application. I'm curious if it's possible to include hyperlinks within the body of these text messages. Is there a method to achieve this? I have attem ...

The process of retrieving request data from axios.get and storing it in the Redux store

Recently delving into Redux, I'm curious about how to retrieve request data from a GET method. Upon mounting the component, you can use axios to send a GET request to '/api/v3/products', passing in parameters like pageNumber and pageSize. ...

Utilize JavaScript to parse JSON response data, calculate the average of a specified field while keeping track of

The data returned from the API call is structured as follows: var array = {"scores":[ { userid: "1", mark: 4.3 }, { userid: "1", mark: 3.8 }, { userid: "2", mark: 4.6 }, { userid: "2&quo ...

A step-by-step guide on how to fetch data by id using Vue.js and Laravel

One of my challenges involves managing a database table named candidate_profiles which consists of various columns such as 'user_id', 'photo_id', 'resume_id', 'video_one_id', 'video_two_id', 'video_thr ...

Azure Chatbot that logs conversations in Webchat whenever the user selects 'none of the above' option

Recently, I've delved into the world of web chat services and embarked on a journey to craft a chat bot using pure JavaScript code that can seamlessly integrate into any HTML file. Despite consulting Microsoft's documentation, I find myself in a ...

Converting ed25519 private key into OpenSSH Format using JavaScript

After generating an ed25519 key pair using the javascript crypto library, I am now faced with the challenge of saving the private key in openssh format. Despite attempting to use the sshpk library for this task, I encountered an issue where the exported k ...

What is the best way to choose a single li element?

I am working on creating a reservation system using HTML, CSS, and JS. I want to customize the color of the border for each list item (li). However, I want only one li to be selected at a time. When I click on a different li, it should remove the selection ...