I have a computed property countryName which returns a country name based on a country code and works fine. I need the use the countryName value as the value of the label of the country data property but I get undefined.
export default {
props: ['content'],
data () {
return {
countries: require('../../plugins/countries'),
country: {
value: this.content.country_code,
label: this.countryName
}
}
},
computed: {
countryName () {
return this.countries.find(item => item.value === this.content.country_code).label
}
}
}
When the component is instantiated, the data function is called before the computed properties are added to the component. That's why you get undefined. Try setting it in mounted or created.
data () {
return {
countries: require('../../plugins/countries'),
country: {
value: this.content.country_code,
label: null
}
}
},
computed: {
countryName () {
return this.countries.find(item => item.value === this.content.country_code).label
}
},
mounted(){
this.country.label = this.countryName
}
For the curious, this is the initState function as of Vue 2.3.3
function initState (vm) {
vm._watchers = [];
var opts = vm.$options;
if (opts.props) { initProps(vm, opts.props); }
if (opts.methods) { initMethods(vm, opts.methods); }
if (opts.data) {
initData(vm);
} else {
observe(vm._data = {}, true /* asRootData */);
}
if (opts.computed) { initComputed(vm, opts.computed); }
if (opts.watch) { initWatch(vm, opts.watch); }
}
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