[Vuejs]-How to know when Vue component has finished initializing completely?

2👍

You could use an array of boolean flags, for however many things you need to watch. They are all initialized in a single array as false, and each watcher is in charge of setting a different index to true. Once all watchers have run, all the flags are true and by watching that array you can tell when everything has been initialized.

export default {
  data() {
    return {
      initialized: [false, false],
      watch1: null,
      watch2: null,
      isDone: false
    }
  },
  watch: {
    watch1(newVal) {
      if (newVal) {
        this.initialized[0] = true
      }
    },
    watch2(newVal) {
      if (newVal) {
        this.initialized[1] = true
      }
    },
    initialized: {
      handler: function (newVal) {
        if (newVal.every(i => i)) {
          this.isDone = true // initialization is completely done
        }
      },
      deep: true
    }
  },
  created() {
    setTimeout(() => {
      this.watch1 = 'some value1'
    }, 2000)

    setTimeout(() => {
      this.watch2 = 'some value2'
    }, 3000)
  }
}

Vue Playground example

👤yoduh

1👍

You can use Promise. In Promise, you can wait for multiple values to return, and then return all the arrived values.

In your code:

function getDefaultValue() {
  return new Promise(async (resolve, reject) => {

    // first interface
    const first = await first()

    // second interface
    const second = await second()
 
    ......

    resolve({first, second, ...})
  })
}

use:

getDefaultValue().then(({first, second, ...}) => {})
👤Gleen

Leave a comment