Let's say I have a basic page with VueJS as follows:
Vue.component('child', {
template: '<p>Placed at index {{index}}</p>',
data() {
return {
index: 0
}
},
mounted() {
this.index = this.$parent.addElement(this);
}
});
new Vue({
el: '#theParent',
data() {
return {
allElements: []
}
},
methods: {
addElement(elem) {
this.allElements.push(elem);
return this.allElements.length - 1;
}
}
});
<script src="https://cdn.jsdelivr.net/vue/2.3.2/vue.min.js"></script>
<div id="theParent">
<child></child>
<child></child>
<child></child>
</div>
The purpose of the output is just to illustrate at what index the elements have been inserted at. My use case requires that the elements are added in the same order that they appear in the HTML. Every time I run this page it appears that this is indeed happening as the output is in order.
My question is: Is this behavior guaranteed to always happen - will VueJS always execute mounted() on components in the order they appear in the HTML? If not, is there an alternate way to guarantee that they are added to my array in the proper order?