I'm reading through this documentation on Vue components, but using Vuex data for my component properties.
From the example, if country_id
is in the data
method it works fine. But when country_id
is a computed property returning data from the Vuex store, the child component's internalValue
is 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>
Your parent component passes the value it has for country_id
to its child component before the mounted
lifecycle hook fires. Since your $store.dispatch
doesn't happen until then, it is initially undefined
.
Your child component sets its internalValue
in its mounted
lifecycle hook with the initial value
prop of undefined
. Then, when country_id
updates in the parent, your child component's value
property will update, but the internalValue
will remain undefined
.
You should make internalValue
a computed property as well:
computed: {
internalValue() {
return this.value;
}
}
Alternatively, you could wait to render the child component until country_id
is defined:
<child v-if="country_id !== undefined" v-model="country_id"></child>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With