【问题标题】:Get the value of a computed property in Vue.js and use it in a data property在 Vue.js 中获取计算属性的值并在数据属性中使用它
【发布时间】:2017-11-09 09:43:21
【问题描述】:

我有一个计算属性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
        }
    }
}

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    当组件被实例化时,数据函数被调用计算属性被添加到组件中。这就是你得到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
    }
    

    出于好奇,这是 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); }
    }
    

    【讨论】:

    • 完美,谢谢。我会在几分钟后标记为已回答。
    • 我不得不使用 created() 而不是 mounted() 并设法放弃计算属性 created () {this.country.label = this.countries.find(item => item.value === this.content.country).label}
    • 由于某种原因,mounted() 无法正常工作。不过感谢您的帮助。
    猜你喜欢
    • 2016-08-09
    • 2020-11-26
    • 2021-04-18
    • 2017-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    相关资源
    最近更新 更多