2017-12-07 6 views
1

created()中にフェッチしたdbオブジェクトを反復しようとしていますが、console.logでは値を取得しますが、v-forテンプレートの部分は空のままです。私の副次的な質問は:この良い習慣は?私はVueの新機能です。この問題に関する私の検索では、それがライフサイクルの問題だと思っています。動的アイテムのv-forでの反復

ありがとうございました。

TEMPLATEのPART:

.content(v-for="(content, key, index) in contents") 
    h3 {{key}} 
    .line 
    | {{getValue(content)}} // this is blank 

方法PART:

getValue(value) { 
    PagesService.fetchDataWrap({ 
    id: value 
    }).then((response) => { 
    const test = response.data.values[0].value 
    console.log(test) //this is working and gives the right value 
    return test 
    }) 
}, 
getPage() { 
    PagesService.fetchPage({ 
    id: this.$route.params.page 
    }).then((response) => { 
    this.name = response.data.result.name 
    this.langs = response.data.result.langs 
    this.project = response.data.result.parent 
    this.contents = response.data.result.values 
    }) 
    this.getProject() 
} 

にconsole.log(this.contents)結果:私は時に送信する値である

{__ob__: Observer} 
footer: "5a29943b719236225dce6191" 
header: "5a29a9f080568b2484b31ee1" 

v - 内容を反復するためにgetValueが処理して対応する値を取得できる

+0

/どこをレンダリングするためにロードされていることを信頼することができますあなたは 'getPage()'を呼び出しますか?あなたが 'async' /' await'を使う理由が見えません。あなたのメソッドは何も返さず、非同期操作を使って完了しません。 – Phil

+0

'getPage()'がコンポーネントの 'created()'部分で呼び出された場合、メソッドは正しい値を返します。 – Sunkhern

+0

いいえ、そうではありません。実際には、彼らは何も返さない – Phil

答えて

1

私は出力に非同期メソッドの値を試みることをお勧めしません。正しく動作することはほとんどありません。

代わりに、createdフックの間に完全にあなたcontents配列/オブジェクトを取り込みます。たとえば、これはfetchDataWrapから戻ってきたものは何でもしてcontentsハッシュ値を置き換えることができます...

getPage() { 
    PagesService.fetchPage({ 
    id: this.$route.params.page 
    }).then(response => { 
    this.name = response.data.result.name 
    this.langs = response.data.result.langs 
    this.project = response.data.result.parent 

    let contents = response.data.result.values 
    Promise.all(Object.keys(contents).map(key => { 
     // map each key to a "fetchDataWrap" promise 
     return PageService.fetchDataWrap({ 
     id: contents[key] 
     }).then(res => { 
     replace the hash with the resolved value 
     contents[key] = res.data.values[0].value 
     }) 
    }).then(() => { 
     // all done, assign the data property 
     this.contents = contents 
    }) 
    }) 
} 

その後、あなたはコンテンツが

.content(v-for="(content, key, index) in contents") 
    h3 {{key}} 
    .line 
    | {{content}} 
+1

うわー!私はこの「Promise.all」を試してみましたが、私の解決策を試してみましたが、うまく動作しませんでした!助けてくれてありがとう、それは私にVueの理解を一杯与えました。 – Sunkhern