Here is a sample list:
var v = new Vue({
'el' : '#app',
'data' : {
'list' : [1,2,3,4,5,6,7,8,9,10]
},
methods: {
activateClass($event){
$event.target.classList.remove('animate');
void $event.target.offsetWidth;
$event.target.classList.add('animate');
},
changeRandomValue(){
var randomAmount = Math.round(Math.random() * 12);
var randomIndex = Math.floor(Math.random() * this.list.length);
Vue.set(this.list, randomIndex, randomAmount)
}
},
mounted(){
var vm = this;
setInterval(function(){
vm.changeRandomValue();
}, 500);
}
})
.animate{
animation: fade 0.5s;
}
@keyframes fade{
0% { background:blue; }
100% { background:white; }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
<ul>
<li v-for="item in list" v-html="item" @click="activateClass($event)"></li>
</ul>
</div>
When you run the above code snippet and click on an li element, it will execute the following code:
activateClass($event){
$event.target.classList.remove('animate');
void $event.target.offsetWidth;
$event.target.classList.add('animate');
}
This adds a class to trigger an animation. Cool!
Additionally, there is a changeRandomValue()
function that randomly updates an element's value in the list.
How can I call the activateClass
method from within the changeRandomValue
method?
I've considered using custom events on the element, like:
<li v-for="item in list" v-html="item"
@click="activateClass($event)"
@myValueChanged="activateClass($event)"
></li>
However, it seems like this approach isn't supported. I also explored watchers, but they don't seem applicable here.
I can identify the clicked element and retrieve its associated data, but I'm struggling to link the updated data back to its corresponding DOM element.
I'm avoiding class bindings because I need to trigger a reflow. Perhaps there's an easy way to accomplish this in Vue that I'm not aware of.