Search code examples
javascriptvue.jsvuejs2vuejs3vue-component

is it possible to make a computed-property lazy


as shown in the below posted code, in compPropsIsBtnDigitizePolygonDisabled, it checks first if digitizePolygonInteractions is initialized or not, if it is not initialized, an error will be thrown.

at the time of execution,initially, the digitizePolygonInteractions is not initialized yet, and the compPropsIsBtnDigitizePolygonDisabled behaves as if it is eager not lazy,thus the error is always thrown because by the time the computer-property executes, the digitizePolygonInteractions is not initilized.

my questions are: 1-is it possible to make compPropsIsBtnDigitizePolygonDisabled` lazy not eager?

2- how to display value of digitizePolygonInteractions within the thrown error

code:

computed: {
    compPropsIsBtnDigitizePolygonDisabled() {
        if (digitizePolygonInteractions) {
            if (isBtnDigitizePolygonClicked.value == true) {
                digitizePolygonInteractions.remove();
                return values.CONST_STRING_DIGITIZE;
            } else {
                digitizePolygonInteractions.add();
                return values.CONST_STRING_STOP_DIGITIZE;
            }
        } else {
            throw new Error('WTF.digitizePolygonInteractions is:', digitizePolygonInteractions)
        }
    },
}

Solution

  • Is it possible to make compPropsIsBtnDigitizePolygonDisabled` lazy not eager ?

    Ideally, computed properties in Vue are eagerly by default but to make it lazy you can use data property and watcher together.

    Example :

    data() {
      return  {
        isComputedPropertyInitialized: false
      }
    },
    computed: {
      compPropsIsBtnDigitizePolygonDisabled() {
        if (!this.isComputedPropertyInitialized) {
          return;
        } else {
          // You can add your logic here
        }
      }
    },
    watch: {
      digitizePolygonInteractions(value) {
        if (!this.isComputedPropertyInitialized && value) {
          this.isComputedPropertyInitialized = true;
        }
      }
    }
    

    How to display value of digitizePolygonInteractions within the thrown error ?

    You can concatenate the error by using + operator in your Error function call.

    throw new Error('WTF.digitizePolygonInteractions is: ' + digitizePolygonInteractions)