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!
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With