Vue.js计算值返回未定义

时间:2020-04-27 14:52:39

标签: vue.js computed-properties

我很难弄清楚这段代码在做什么。

    name: 'StatementInfo',
    data() {
        return {
            currentStatement: {
                client: '',
                clientEmail: '',
                date: '',
                hours: '',
                hourlyRate: '',
                total: this.calcTotal
            }
        }
    },
    computed: {
        calcTotal () {
            return parseInt(this.hours) * parseInt(this.hourlyRate)
        }
    },
    methods: {
        saveForm () {
            console.log(this.currentStatement)
            this.$emit('save-form', this.currentStatement)
        },
  }

控制台记录this.currentStatement导致total不确定,但是从初级开发人员的角度来看,我会想象这可行。能不能再有经验的人对此提出建议呢?

2 个答案:

答案 0 :(得分:0)

computed methods相关的反应性不是这样。

data的内容将被评估一次,此时this.calcTotal尚未定义。在更新之前,该值将保持不变。

需要时应直接使用计算方法。

因此,请使用calcTotal而不是total

答案 1 :(得分:0)

尝试为this.hours和this.hourlyRate = 0分配默认值, 也许当您执行saveForm()时,该变量为null或未定义

相关问题