0

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

drake035
  • 3,955
  • 41
  • 119
  • 229

1 Answers1

1

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/

Laurens
  • 2,596
  • 11
  • 21
  • Doesn't work. And in theory my code already make the class dependent on the `event.active` value. – drake035 Jan 27 '19 at 12:46
  • Why wouldn't it work? Can you print your example where you tried this and it doesn't work? Works perfectly fine in this jsfiddle: https://jsfiddle.net/84zhx1et/ – Laurens Jan 27 '19 at 12:49
  • @drake035 See my updated answer to see the solution for what I think is going wrong in your scenario – Laurens Jan 27 '19 at 12:56
  • Thanks, you're my man! I didn't know Vue cannot detect property additions, now I do (https://vuejs.org/v2/api/#Vue-set) – drake035 Jan 27 '19 at 14:46