【问题标题】:Computed property that depends on another computed property依赖于另一个计算属性的计算属性
【发布时间】:2020-05-17 23:20:41
【问题描述】:

下面的代码产生错误“无法读取未定义的属性'form'”:

computed: {
  boundary_limits () {
    return this.$refs.hemoBoundaryLimits.form;
  },
  high_risk_alerts () {
    return this.$refs.highRiskAlerts.form;
  },
  alerts () {
    return {
      boundary_limits: this.boundary_limits,
      high_risk_alerts: this.high_risk_alerts
    }
  }
}

如果我删除了alerts(),我不会收到任何错误,我什至可以控制台记录boundary_limitshigh_risk_alerts 成功,这意味着 $refs.hemoBoundaryLimitsthis.$refs.highRiskAlerts 定义。

所以 Vue.js 对我如何定义 alerts 有问题,但我认为它没有问题。

有什么线索吗?

【问题讨论】:

  • 你到底有什么错误?

标签: vue.js computed-properties


【解决方案1】:

出现错误是因为您试图在计算属性中访问$refs。 计算属性在安装模板之前进行评估,因此hemoBoundaryLimitsundefined

你应该在挂载的钩子中访问$refs

作为解决方案,您可以通过使用@hook 事件知道何时安装组件来欺骗它:

<hemoBoundaryLimits @hook:mounted="isHemoBoundaryLimitsMounted = true" />

在脚本中

data: () => ({
  isHemoBoundaryLimitsMounted: false
}),

computed: {
  boundary_limits () {
    if (!this.isHemoBoundaryLimitsMounted) return
    return this.$refs.hemoBoundaryLimits.form;
  }
}

【讨论】:

    猜你喜欢
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-23
    • 2018-08-11
    • 2017-06-07
    • 2020-02-05
    • 1970-01-01
    相关资源
    最近更新 更多