[Vuejs]-How to access store in the mounted() method with NUXT.js?

0πŸ‘

  1. First of all, you shall be able to read from its Vue component instance in mounted(). such as
mounted() {
  this.$store;
}
  1. But the problem is this.$store is not guaranteed to be available at the time of mounted() being called.

While i am still figuring it out, I debug and notice that this.$store is not immediately available but will be available after certain time of mounted.

enter image description here
enter image description here

As of today, there is no official documentation that I could found describing at what point Vuex will be ready in the lifecycle. But I think fetch and its state looks promising. I will try and report back.

πŸ‘€xinbenlv

0πŸ‘

As $store is not enable immediately and you can’t determine it, you can test it and us it only when available using this :

mounted() {
    while (!this.$store) {
      // Do nothing
    }
    this.$store.commit('xxxx/xxx');
},
  1. The while loop will loops again and again untill this.$store is not resolved to undefined anymore.
  2. As the while loop is not looping anymore, the this.$store.commit('xxxx/xxx'); line will be executed !!

With the help of this little trick, I can use this.$store as soon as it is available, directly with the help of the mounted method.

Leave a comment