Reputation: 401
I am new to vue.js but I have a simple question. I followed a tutorial but I want to extand it just a tiny bit :-P
Everytime when my rank changes I want to add a css class to animate the label. How can I do this little thing?
<div id="app">
<h1>Current Rank: <strong>{{ rank }}</strong></h1>
<p>Your XP: <strong>{{ xp }}</strong></p>
<button @click="increase">+ 10 XP</button>
<button @click="decrease">- 10 XP</button>
</div>
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"; }
}
} });
https://jsfiddle.net/0caprx4L/
Upvotes: 1
Views: 1651
Reputation: 60143
There are probably a number of ways to do this, but I think the simplest is to use Vue.js transitions.
Below is a working example. The most relevant portion of the code is this:
<transition name="highlight" mode="out-in">
<h1 :key="rank">Current Rank: <strong>{{ rank }}</strong></h1>
</transition>
The :key="rank"
part makes sure that the h1
element has a different key when the rank changes. This prevents Vue.js from reusing the same element and instead causes the old element to be removed and the new one to be added. This triggers the transition we've set up with the name highlight
. (See the CSS for how that animation is done.) Also note the mode
of out-in
, which makes sure that the leave animation happens before the enter animation. (Without this, there's an overlap where both the old rank and new rank are visible at the same time.)
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/[email protected]/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>
Upvotes: 6