N
N
nurdus2018-07-01 12:38:13
Vue.js
nurdus, 2018-07-01 12:38:13

How to implement adding classes to vue list via computed?

Good afternoon.
There is such a list (the code works):

<tr v-for="job in jobs" :key="job._id" :class="[ 
  job.state,
  job.isRead ? '' : 'no-read', 
  new Date() >= Date.parse(job.finalDate) ? 'overdue' : ''
  ]">
  <td>{{ job.subject }}</td>
  <td>{{ job.executor }}</td>
</tr>

I wanted to make it a little more beautiful by moving the class calculation to "computed", but nothing happens, I can't pass the current record, I tried this (the code below does not work):
<tr v-for="job in jobs" :key="job._id" :class="jobClass(job)">
  <td>{{ job.subject }}</td>
  <td>{{ job.executor }}</td>
</tr>

computed: {
  jobClass: function(job) {
    return {
      done: job.state,
      break: job.state,
      //...
    }
  }
}

writes that jobClass is not a function, if classs="jobClass" to do, then how to pass job to computed?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2018-07-01
@nurdus

writes that jobClass is not a function

Well, put it in methods. Do not try to use the tool in an unintended way.

E
egerr, 2020-01-16
@egerr

if you use computed to work with classes, then it looks like this

countColor() {
        return {
          red: this.comment.rating.count < 0,
          green: this.comment.rating.count > 0,
        };
      },

and in the template :class="countColor"
in your case, computed will not work, because you cannot pass a parameter to it that will be known when rendering the list. you just need to write a method (in methods) that will also return the name of the class you need. Below is a piece of my code, which is essentially the same, only it will need to be rewritten with an input parameter:
categoryTitle() {
        let catTitle = '';
        if (!this.$route.params.category) {
          catTitle = 'Новости<br> игрового мира';
        }
        if (this.$route.params.category === 'news') {
          catTitle = 'Новости';
        }
        if (this.$route.params.category === 'articles') {
          catTitle = 'Статьи';
        }
        return catTitle;
      },

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question