Ahmad Mobaraki
Ahmad Mobaraki

Reputation: 8160

Toggle element class with VueJs2 inside v-for, is this the right way?

I read VueJs docs, It recommends to use computed property to calculate or toggle an element class, but I couldn't do it inside v-for loop. What I have done instead is this:

Template

<li v-bind:click="onClick(word)"  v-bind:class="calculateClass(word)"  v-for="word in words">{{ word.name }}</li>

Code

data: {
  words : [{name:'ali', clicked : 1},{name:'sara', clicked : 0},{name:'marya', clicked : 1}]
},

methods: {
  calculateClass : function (word) {
    return {
      "classA": word.clicked=== 1,
      "classB" : word.clicked === 0,
      'test' : true // allways return 'test' class
    }
  },

  onClick: function (word) {
    // changing the `clicked` property of related object in this.words array
    for (var i in this.words) {
      if (this.words[i].name === word.name) {
        this.$set(this.words[i], 'clicked', 1)
        break; //Stop this loop, we found it!
      }
    }
  }
},

It is working, but is there a problem with this approach? I didn't see other examples using a method to calculate a class. Should I do this with computed? How? Is there a better way?

Upvotes: 1

Views: 98

Answers (1)

Bert
Bert

Reputation: 82449

You are correct that a computed property cannot accept an argument and, as such, doesn't really fit in this case.

There is nothing wrong with using a method the way you are.

Upvotes: 1

Related Questions