Vuex + VueJS: Passing computed property for undefined child
I am reading this documentation on Vue components but using Vuex data for my component properties.
In the example, if country_id
in a method data
, it works fine. But when country_id
is a computed property that returns data from the Vuex store, the child component is internalValue
always initialized as undefined
.
What am I doing wrong?
Parent component:
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>
Child component:
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>
source to share
Your parent component passes the value it has to country_id
its child component before the lifecycle hook is fired mounted
. Since yours is $store.dispatch
not satisfied until then, it is originally undefined
.
Your child component sets its own internalValue
in its lifecycle hook mounted
with the original value
prop undefined
. Then, when country_id
updated on the parent, your child component property value
will update, but internalValue
will remain undefined
.
You should also make a internalValue
computed property:
computed: {
internalValue() {
return this.value;
}
}
Alternatively, you can wait until the child component is selected before country_id
:
<child v-if="country_id !== undefined" v-model="country_id"></child>
source to share