2017-12-08 8 views
1

私はVue Resourceを使用して、REST APIからイメージコレクションを取得しています。リクエストは、私のVueコンポーネントのフックcreatedで送信されます。データがロードされる前にマウントされたメソッドが起動される - VueJS

問題は、私はmountedフックで取得したデータにアクセスしようとしていますが、データがロードされていないことです。

私は、コンソールにこのエラーが表示されます。ここでは

[Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'forEach' of undefined"

は私のコンポーネントです:

<script> 
export default { 
    data() { 
    return { imgs : '' }; 
    }, 
    created() { 
    // the full url is declare in my main.js 
    this.imgs = this.$resource('acf/v3/pages/4'); 

    this.imgs.query().then((response) => { 
     console.log('success', response); 
     this.imgs = response.data.acf.gallery; 
    }, (response) => { 
     console.log('erreur', response); 
    }); 
    }, 
    mounted() { 
    // get the ref="image" in my dom template 
    let imgs = this.$refs.image; 

    imgs.forEach((img) => { 
     // I do some stuff with imgs 
    }); 
    } 
} 
</script> 

私はmountedのコンテンツの周囲setTimeoutをラップした場合、すべてが正常に動作します。

したがって、mountedフックが実行される前にデータがロードされるのを待つ方法がわかりません。これはVueのライフサイクルフックの役割ではありませんか?

+0

なぜ、created()を使用しないのですか? – samayo

+0

'created'には何も反応しないので。 'mounted'フックの前にDOMを操作することはできません。 [この文書をチェック](https://alligator.io/vuejs/component-lifecycle/)。これは、lifCycleフックを1つだけ使用する場合とまったく同じ問題です。私のコンテンツは、私がそれを使いたいときに読み込まれません。 – BrownBe

答えて

2

this.imgs.query()呼び出しは非同期なのでthenハンドラは(私は属性ref="image"を使用して、テンプレート内の要素にv-forにバインドされていると仮定しています)this.imgsを設定する前に、あなたのmountedフックが呼び出されています。したがって、コンポーネントがDOMにマウントされていても、$refsはまだセットアップされていません。

"imgsで何かをする"メソッドを作成し、非同期呼び出しのthenハンドラの$nextTick callbackでそのメソッドを呼び出します。 $nextTickに渡されるコールバックは、「次のDOM更新サイクルの後に実行されます。」つまり、$refsがその時点で設定されることを意味します。

<script> 
export default { 
    data() { 
    return { imgs: '' }; 
    }, 
    created() { 
    // the full url is declare in my main.js 
    this.imgs = this.$resource('acf/v3/pages/4'); 

    this.imgs.query().then((response) => { 
     console.log('success', response); 
     this.imgs = response.data.acf.gallery; 
     this.$nextTick(() => this.doStuffWithImgs()); 
    }, (response) => { 
     console.log('erreur', response); 
    }); 
    }, 
    methods: { 
    doStuffWithImgs() { 
     // get the ref="image" in my dom template 
     let imgs = this.$refs.image; 

     imgs.forEach((img) => { 
     // I do some stuff with imgs 
     }); 
    } 
    } 
} 
</script> 
+0

私は[$ nextTick](https://fr.vuejs.org/v2/api/index.html#Vue-nextTick)を知らなかった。ありがとうございます、それは期待通りにうまく動作しています。 – BrownBe

関連する問題