Search code examples
vue.jscomputed-properties

Computed property that depends on another computed property


Code below yields error "Cannot read property 'form' of undefined":

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
    }
  }
}

Yet if I removed alerts(), I get no error and I can even console log boundary_limits or high_risk_alerts successfully, which means $refs.hemoBoundaryLimits and this.$refs.highRiskAlerts are defined.

So Vue.js has a problem with how I define alerts, but I see no problem in it.

Any clue what's going on?


Solution

  • The error comes because you are trying to access $refs in computed property. Computed properties are evaluated before the template is mounted and thus the hemoBoundaryLimits is undefined.

    You should access $refs in the mounted hook.

    As solution, you can trick it by knowing when the component is mounted using @hook event:

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

    And in the script

    data: () => ({
      isHemoBoundaryLimitsMounted: false
    }),
    
    computed: {
      boundary_limits () {
        if (!this.isHemoBoundaryLimitsMounted) return
        return this.$refs.hemoBoundaryLimits.form;
      }
    }