Is VueJS guaranteed to call mounted() in correct order?

Viewed 1934

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?

1 Answers

from my experience with Vue and Ag-Grid extension, it's not always the case.

To make sure it's loaded in the correct order, I implement watch function to let Vue know the DOM is ready.

even with beforeMount or created wont't help if the DOM element is somehow late-triggered.

  computed: {
    elementWatcher () {
      return this.whateverDOMElement // after this child is ready
    }
  }

  watch: {
    elementWatcher (val) {
      if (val) {
        this.mountAnother() // parent can be mounted
      }
    }
  }
Related