获取Vue.js中计算属性的值,并在数据属性中使用它

Jac*_*ham 1 javascript vue.js vuejs2

我有一个计算属性countryName,它根据国家代码返回一个国家名称,并且工作正常.我需要使用该countryName值的价值label的的country数据属性,但我得到的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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ber*_*ert 9

实例化组件时,将计算属性添加到组件之前调用数据函数.这就是你得到的原因undefined.尝试将其设置为mountedcreated.

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
}
Run Code Online (Sandbox Code Playgroud)

对于好奇,这是initStateVue 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); }
}
Run Code Online (Sandbox Code Playgroud)