简体   繁体   中英

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.

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();
    }
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM