Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the value of a computed property in Vue.js and use it in a data property

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
        }
    }
}
like image 568
Jack Barham Avatar asked Jan 21 '26 11:01

Jack Barham


1 Answers

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); }
}
like image 179
Bert Avatar answered Jan 24 '26 01:01

Bert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!