If you're looking for a straightforward way to accomplish this task, utilizing Vue.js transitions is likely the best approach.
Here's an example that demonstrates how it can be implemented effectively:
<transition name="highlight" mode="out-in">
<h1 :key="rank">Current Rank: <strong>{{ rank }}</strong></h1>
</transition>
The use of :key="rank"
ensures that the key for the h1
element changes when the rank is updated. This prevents Vue.js from reusing the existing element and instead removes the old one while adding the new one. As a result, the transition defined by the name highlight
gets triggered (refer to the CSS for specifics on the animation). Additionally, note the mode
attribute set to out-in
, ensuring that the exit animation occurs before the entrance animation. Without this distinction, there would be an undesirable overlap where both the old and new ranks are visible simultaneously.
var app = new Vue({
el: "#app",
data: {
xp: 10
},
methods: {
increase: function() {
return this.xp += 10;
},
decrease: function() {
return this.xp -= 10;
}
},
computed: {
rank: function() {
if (this.xp >= 100) {
return "Advanced";
} else if (this.xp >= 50) {
return "Intermediate";
} else if (this.xp >= 0) {
return "Beginner";
} else {
return "Banned";
}
}
}
});
.highlight-enter-active {
animation: highlight 2s;
}
@keyframes highlight {
0% { background-color: yellow; }
100% { background-color: transparent; }
}
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f0868595b0c2dec4dec2">[email protected]</a>/dist/vue.min.js"></script>
<div id="app">
<transition name="highlight" mode="out-in">
<h1 :key="rank">Current Rank: <strong>{{ rank }}</strong></h1>
</transition>
<p>Your XP: <strong>{{ xp }}</strong></p>
<button @click="increase">+ 10 XP</button>
<button @click="decrease">- 10 XP</button>
</div>