I am attempting to attach an event to dynamically rendered elements, and below is my approach.
<div id="app">
<a href="#" @click="loadData">Load Data</a>
<ul>
<li class="collections" v-for="item in collections" :key="item.id">{{ item.name }}</li>
</ul>
</div>
new Vue({
el : '#app',
data : {
files : []
},
mounted(){
const _self = this;
axios.get('myapi.com/api/users',{})
.then(function(res){
_self.files = res.data.users;
// add event
document.querySelectorAll('.collections').forEach(function(el){
_self.$ons.GestureDetector(el).on("hold", function(event) {
alert();
});
});
});
},
computed : {
collections(){
return this.files;
}
},
methods : {
loadData(){
const _self = this;
axios.get('myapi.con/api/users/2',{})
.then(function(res){
_self.files = res.data.users;
document.querySelectorAll('.collections').forEach(function(el){
_self.$ons.GestureDetector(el).on("hold", function(event) {
alert();
});
});
});
}
}
});
It appears that updating the DOM element is done asynchronously. When I tried
console.log(document.querySelectorAll('.collections').length)
, it returned 0
. However, checking via console showed the correct number of target elements.
Note: manually binding the event serves a specific purpose, even though I could use the standard @click in Vue.