Leah
Leah

Reputation: 365

Vue.js css transition on class change

I am trying to use the css transition property to fade the #app background from black to white by adding a class of .lightTheme. The adding of .lightTheme class works as expected, but the transition does not.

Do I have to add the Vue transition element? And if so how? #app is not leaving/entering the dom - I just want to animate it's properties (and I don't want to add unnecessary code if possible!

HTML

<div id="app" v-bind:class="{ lightTheme: isActive }">
   <button v-on:click="toggleTheme">Change theme</button>
</div>

JS

new Vue({
    el: '#app',

    data: {
        isActive: false
    },

    methods: {
      toggleTheme: function(){
          this.isActive = !this.isActive;
        // some code to filter users
      }
    }

});

CSS

#app {
    background: black;
    transition: 1s;
}

#app.lightTheme {
    background: white;
}

Thanks!

Upvotes: 9

Views: 11679

Answers (1)

wegelagerer
wegelagerer

Reputation: 3710

To answer your question if you have to use transition for something like this, the answer is no. The solution you proposed should work out of the box.

There is probably something else that is interfering with your code, but the one you posted is correct.

I attached the working snippet.

new Vue({
    el: '#app',
    data: {
        isActive: false
    },
    methods: {
      toggleTheme: function(){
          this.isActive = !this.isActive;
      }
    }
});
#app {
    background: black;
    transition: 1s;
}

#app.lightTheme {
    background: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script>
<div id="app" :class="{ lightTheme: isActive }">
   <button @click="toggleTheme">Change theme</button>
</div>

Upvotes: 12

Related Questions