drake035
drake035

Reputation: 2877

Toggling classes of individual li elements by click in a v-for

After over an hour trying unsuccessfully to implement that answer into my app I decided to ask help here. My li items' class won't toggle and I can't figure out why. Here's my code:

HTML:

<li :class="classObject(event)" v-for="event in events" @click="showEvent(event)">
  ...
</li>

JS:

methods: {
  classObject(event) {
    return {
      active: event.active,
      'event': true
    };
  },
  showEvent: function(event) {
    event.active = !event.active;
  }
},
mounted() {
  axios.get(this.eventsJsonUrl)
    .then(response => {
      this.events = response.data;
      this.events.map((obj) => {
        obj.active = false;
        return obj;
      })
    })
}

Note that my events array of object doesn't initially have an active property, I'm adding it in mounted hook.

Just in case here's a console.log of the resulting events array:

enter image description here

Upvotes: 0

Views: 32

Answers (1)

Laurens
Laurens

Reputation: 2607

Make the class dependent on the variable like this:

<li class="event" :class="{ active: event.active }" v-for="event in events" @click="showEvent(event)">
  ...
</li>

Where the function showEvent toggles the event.active variable like you already have.

EDIT: see this jsfiddle to see that this works: https://jsfiddle.net/84zhx1et/

EDIT 2: I see what is going wrong in your example now: You are trying to dynamically add the active property to the events, but VueJs won't trigger this change. You can set the property like this to make sure VueJs re-renders the events:

  this.events.map((obj) => {
    this.$set(obj, 'active', false)
  })

See this JsFiddle which uses this method: https://jsfiddle.net/84zhx1et/1/

Upvotes: 1

Related Questions