Stephan-v
Stephan-v

Reputation: 20359

Vue object properties not changing with v-bind:class

I have a object which kind of looks like this:

{
    data: [
        {
            id: 28,
            type: "blabla",
            name: "myname",
            language: "en",
            active: true
        },
        {
            id: 5,
            type: "blabla",
            name: "myname2",
            language: "fr",
            active: false
        },
        // etc
    ]
}

I have split this object up into groups which I am display like this:

<li class="suggestion" v-for="suggestion in group">
    <a href="#" :class="{ active: suggestion.active }"></a>
</li>

I want to highlight my results so that is why I have a position property on my Vue object. which can be changed.

I have a watcher set up for the position attribute:

position() {
    this.suggestions.forEach((suggestion, index) => {
        suggestion.active = index === this.position;
    });
}

It will make the current position(so the currently item active). This works fine when I am checking the array of objects and their properties. The items change their .active property perfectly. But the class binding does not seem to re-evaluate.

What is going wrong here? The initial active state does get taken into account and my first item is highlighted perfectly fine.

Nothing happens on a change to the actual classes though yet with the Vue devtools I can see perfectly fine that the objects properties are changing.

Upvotes: 1

Views: 1921

Answers (1)

peaceman
peaceman

Reputation: 1721

So the problem was that if object gets created like this:

object[suggestion.type].push(suggestion);

Vue doesn't detect changes to that object. It has to do with how Vue watches objects for changes.

In order for Vue to play nicely with objects you create and want to be reactive you need to utilize Vue.set

Vue.set(object, suggestion.type, suggestion)

Or

this.$set(object, suggestion.type, suggestion)

Upvotes: 3

Related Questions