2017-05-18 7 views
3

私はこのdocumentation on Vue componentsを通して読んでいますが、コンポーネントのプロパティにはVuexデータを使用しています。Vuex + VueJS:計算されたプロパティを子に渡すことは定義されていません

この例では、country_iddataメソッドにある場合、正常に動作します。しかし、country_idがVuexストアからデータを返す計算されたプロパティである場合、子コンポーネントのinternalValueは常にundefinedとして初期化されます。

私は間違っていますか?

親コンポーネント:

export default { 
    computed: { 
     country_id() { 
      return this.$store.state.user.country_id 
     } 
    }, 
    mounted: function() { 
     this.$store.dispatch('user/load'); 
    } 
} 
<template> 
    <child v-model="country_id"></child> 
</template> 

子コンポーネント:

export default { 
    props: [ 'value' ], 
    data: function() { 
     return { 
      internalValue: null, 
     }; 
    }, 
    mounted: function() { 
     this.internalValue = this.value; 
    }, 
    watch: { 
     'internalValue': function() { 
      this.$emit('input', this.internalValue); 
     } 
    } 
}; 
<template> 
    <p>Value:{{value}}</p> 
    <p>InternalValue:{{internalValue}}</p> 
</template> 

答えて

0

あなたの親コンポーネントはmountedライフサイクルフック発生する前に、それはその子コンポーネントにcountry_idために持っていた値を渡します。 $store.dispatchはそれまでに発生しないため、最初はundefinedです。

あなたの子コンポーネントはundefinedの初期value小道具とそのmountedライフサイクルフックでそのinternalValueを設定します。親の中でcountry_idが更新されると、子コンポーネントのvalueプロパティが更新されますが、internalValueundefinedのままになります。

あなたにもinternalValue計算されたプロパティを作成する必要があります。

<child v-if="country_id !== undefined" v-model="country_id"></child> 

また
computed: { 
    internalValue() { 
    return this.value; 
    } 
} 

country_idが定義されるまでは、子コンポーネントをレンダリングするために待つことができます

関連する問題