我有一个计算属性 countryName
,它根据国家代码返回国家名称并且工作正常。我需要使用 countryName
值作为 country
数据属性的 label
的值,但我得到 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
}
}
}
最佳答案
当组件被实例化时,数据函数在被计算属性添加到组件之前被调用。这就是为什么您得到 undefined
的原因。尝试将其设置为 mounted
或 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
}
出于好奇,这是 Vue 2.3.3 中的 initState
函数
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); }
}
关于javascript - 在 Vue.js 中获取计算属性的值并在数据属性中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44422783/