【问题标题】:Vue.js computed value returning undefinedVue.js 计算值返回未定义
【发布时间】:2020-08-11 04:08:40
【问题描述】:

我一直无法弄清楚我对这段代码做错了什么。

    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 未定义,但从初级开发人员的角度来看,我会认为这是可行的。有没有更多有经验的人可以看看这个并告诉我它可能是什么?

【问题讨论】:

  • 你能用任何在线代码编辑器如codesandbox等为此创建一个小演示。然后其他人可以更好地调试问题并提供一些解决方案。

标签: vue.js computed-properties


【解决方案1】:

这不是与computed methods 相关的反应性工作方式。

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

您应该在需要时直接使用您的计算方法。

所以使用calcTotal 而不是total

【讨论】:

  • 你的意思是我应该将 currentStatement 中的 total 更改为 calcTotal 还是应该在哪里使用 calcTotal 而不是 total
  • 你应该使用 calcTotal 而不是 total
  • 这似乎不起作用,它返回 NaN 或未定义,你能举个例子说明你的意思吗?
  • 出于这个原因我把parseInt。会不会是我执行不正确?
  • 似乎无论我做什么它总是返回 NaN,要么是那个,要么是未定义的
【解决方案2】:

尝试将默认值赋给 this.hours 和 this.hourlyRate = 0, 也许当你执行 saveForm() 时,变量是 null 或 undefined

【讨论】:

  • 问题在于那些链接到的字段需要占位符才能在页面加载时保持不变。尝试此建议后,它仍然返回 undefined。
猜你喜欢
  • 2021-04-14
  • 1970-01-01
  • 2020-08-04
  • 1970-01-01
  • 2019-03-18
  • 2018-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多