簡體   English   中英

Vuejs - 無法從組件訪問 $root 數據

[英]Vuejs - cannot access $root data from component

我正在使用 vue.js 來管理用戶,並且我有這段代碼來初始化 vue:

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

store我有:

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

這樣,用戶就被正確初始化了。

現在,我還有一個帶有以下內容的 vue 組件:

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

但是init()方法內部的console.log(this.$root.store.user.state.user)導致null ,而內部computed的返回實際用戶。

為什么會這樣? init()方法不應該返回用戶嗎?

謝謝你們。

如果您能夠更改您的init()方法以返回 Promise - 那么您可以在實例化整個 Vue 應用程序之前等待 Promise 解決:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM