0

I loop through a set of users to build a table using VueJS 'for' statement.

There's a column called "approved". If it's true then I want the entire table row to be green. How to achieve that?

                <tbody>
                  <tr v-for="user in users" >
                    <td v-for="key in columns">
                        <!-- At This point I can tell if the user is approved but how to change the style of the parent tr element?? -->
                        <span v-if='key == "approved" && user[key] == 0'>
                            Not Approved
                        </span>

                        <span v-else-if='key == "approved" && user[key] == 1'>
                            Approved!
                        </span>

                        <span v-else>
                            {{user[key]}}
                        </span>
                    </td>
                  </tr>
                </tbody>

2 Answers 2

1

If you always have "approved" column you can simply achieve it in this way:

<tr v-for="user in users" 
    v-bind:style="{backgroundColor: user['approved'] == 1 ? 'green' : '' }">

or

<tr v-for="user in users" 
    v-bind:class="{green: user['approved'] == 1}">


.green {
     background-color: green:
} 
Sign up to request clarification or add additional context in comments.

Comments

0

You can use method to assign class to tr dynamically

<tbody>
  <tr v-for="user in users" :class="{'green': isApprove(user, columns)}">
    <td v-for="key in columns">
        <!-- At This point I can tell if the user is approved but how to change the style of the parent tr element?? -->
        <span v-if='key == "approved" && user[key] == 0'>
            Not Approved
        </span>

        <span v-else-if='key == "approved" && user[key] == 1'>
            Approved!
        </span>

        <span v-else>
            {{user[key]}}
        </span>
    </td>
  </tr>
</tbody>


<script>
  ...
  methods: {
    isApprove(user, columns) {
      for (let idx in columns) {
        const key = columns[idx]
        if (key === 'approved' && user[key] == 1) {
          return true
        }
      }
      return false
    }
  }

</script>

<style>
.green {
  background-color: green;
}
</style>

1 Comment

You can shorten the syntax using arrow functions and the some method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.