Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 667
Leah Avatar asked Oct 04 '17 11:10

Leah


People also ask

How do I bind a dynamic class in Vue?

Adding a dynamic class name is as simple as adding the prop :class="classname" to your component. Whatever classname evaluates to will be the class name that is added to your component. Of course, there is a lot more we can do here with dynamic classes in Vue.

How do you toggle classes at Vue?

We can toggle a class dynamically in vue by passing an object to the v-bind:class attribute. In this example, we are toggling a class by clicking the Toggle button.

What triggers CSS transition?

Transition triggers # Your CSS must include a change of state and an event that triggers that state change for CSS transitions to activate. A typical example of such a trigger is the :hover pseudo-class. This pseudo-class matches when the user hovers over an element with their cursor.


1 Answers

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>
like image 193
wegelagerer Avatar answered Sep 28 '22 05:09

wegelagerer