Skip to content
Advertisement

Vuejs – cannot access $root data from component

I’m using vue.js to manage the user and I have this piece of code to initialize vue:

const app = new Vue({
    el: '#dashboard',
    i18n: i18n,
    data:{ store },
    router: router,
    created()
    {
      this.store.user.actions.getUser();
    }
});

Inside store I have:

const store =
{
  user:
  {
    state:
    {
      user: null
    },
    actions:
    {
      getUser()
      {
        //method to retrieve user usign axios
      }
    }
  }
}

In this way, the user is correctly initialized.

Now, I have also a vue component with the following:

computed:
{
  getUser()
  {
    console.log(this.$root.store.user.state.user)
  }
},
methods:
{
  init()
  {
    console.log(this.$root.store.user.state.user)
  }
},
created()
{
  this.init();
}

But the console.log(this.$root.store.user.state.user) inside the init() method results in null, while the one inside computed returns the actual user.

Why it’s like this? Shouldn’t the init() method returns the user anyway?

Thank you all.

Advertisement

Answer

If you are able to change your init() method to return Promise – then you can wait for that Promise to resolve before instantiating the whole Vue application:

store.init().then(() =>
{
  const app = new Vue({
    el: '#dashboard',
    i18n: i18n,
    data:{ store },
    router: router,
    created()
    {
      this.store.user.actions.getUser();
    }
  });
});
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement