2017-12-15 13 views
0

vueとvuexで計算され、作成された小道具を操作する正しい順序についていくつか質問があります。vuejs/vuexで計算され、作成された小道具の順序

私は、次のコード

<script> 
    import { mapGetters } from 'vuex' 

    export default { 
    data() { 
     return {} 
    }, 
    props: ['id'], 
    methods: { 
    }, 
    computed: { 
     ...mapGetters({ 
     semestre: 'semestre/show/item' 
     }), 
     titre: function() { 
     return this.semestre.nom 
     } 
    }, 
    created() { 
     this.$store.dispatch('semestre/show/retrieve', parseInt(this.id)) 
    } 
    } 
</script> 

を持っているしかし、私は未定義の変数「semestre」を操作し、計算力価に、エラーが発生しています。

計算が作成前に実行されたようです。ですから、Createdの場所でbeforeCreateを使用しようとすると、小道具が存在しないため、動作しません。

だから私は

beforeCreate =>小道具=>計算結果=>作成された?と思いますか

しかし、私のコードを正しく実行するにはどうすればよいですか?私は小道具で値を得て、この値をvuexに渡し、そしてVueXの結果を操作する必要があります。 多分、私はvue/vueXの論理で何かを理解していません。あなたの計算がビューで使用されている場合、あなたのvuexアクションが非同期であることが表示されますので、semestreが提供される前に、

デビッド

答えて

0

おかげで、その後、はい、それは計算されます。非同期の場合、処理が完了する前にcreated関数の実行が終了します。このため、ゲッター'semestre/show/item'は、アクションが完了するまで、常にではなく、となるまで、未定義の値を返します。createdが実行を終了します。

これを処理するには、値の非同期読み込みを処理するようにコンポーネントを記述する必要があります。基本的には、まだロードされていないケースを処理し、ロードされたケースを処理するようにコンポーネントを記述する必要があります。私はそれが未定義またはnull値を処理できるように、あなたの計算を変更するお勧め:

titre: function() { 
    return this.semestre && this.semestre.nom; 
    //or if you want to provide a default value 
    return (this.semestre && this.semestre.nom) || '??'; 
} 

より堅牢なソリューションを使用すると、値があなたのアクションが完了したかどうかを追跡することによってロードされ、ユーザーにフィードバックを提供するものです。

<template> 
    <div v-if="isLoading">Content is load (you could display a spinner)</div> 
    <div v-else> 
     Display your semestre content here: 
     {{titre}} 
    </div> 
</template> 
<script> 
    import { mapGetters } from 'vuex' 

    export default { 
    data() { 
     return { 
      isLoading: false, 
     }; 
    }, 
    props: ['id'], 
    computed: { 
     ...mapGetters({ 
     semestre: 'semestre/show/item' 
     }), 
     titre: function() { 
     return this.semestre.nom 
     } 
    }, 
    async created() { 
     this.isLoading = true; 
     await this.$store.dispatch('semestre/show/retrieve', parseInt(this.id)) 
     this.isLoading = false; 
    } 
    } 
</script> 

そして、あなたは、キーワードを待つ/非同期を使用することができない場合は、次の操作を行うことができます

created() { 
    this.isLoading = true; 
    this.$store.dispatch('semestre/show/retrieve', parseInt(this.id)) 
     .then(() => { 
      this.isLoading = false; 
     }); 
} 
関連する問題