Can’t use computed property in data

I have an array in my data:

data () {
  return {
    steps: [
      {
        disabled: this.someCheck
      }
    ]
  }
}

And a computed property:

computed: {
  ...mapGetters({
    getFinishedSteps: 'jobFound/getFinishedSteps'
  }),

  someCheck () {
    let x = true
    for (const val of this.getFinishedSteps) {
      if (val === ('address_information' || 'contact_information' || 'financiel_information' || 'identity_information')) {
        x = false
      }
    }
    return x
  }
}

And the template:

<ProgressContent
  v-for="(step, n) of steps"
  :key="n"
/>

And the ProgressContent component:

props: {
  step: {
    type: Object,
    default: () => ({
      disabled: false
    })
  },
}

I want to pass the return value of the someCheck computed property into the disabled value in the data but in the ProgressContent component the disabled value is not there (it’s empty).

Answer

You can’t assign a computed to a data property while the data is initializing. Even if you could, it would not be reactive, it would only occur once. If the computed changed, the data property would not.

You could create steps as a computed:

computed: {
  ...mapGetters({
    getFinishedSteps: 'jobFound/getFinishedSteps'
  }),
  someCheck () {
    // ...
  },
  steps() {
    return [{  disabled: this.someCheck }]
  }
}

Or you could use a watch:

data() {
  return {
    steps: [{ disabled: null }]
  }
},
computed: {
  ...mapGetters({
    getFinishedSteps: 'jobFound/getFinishedSteps'
  }),
  someCheck () {
    // ...
  }
},
watch: {
  someCheck: {
    handler(newValue) {
      this.steps[0].disabled = newValue;
    },
    immediate: true
  }
},

Leave a Reply

Your email address will not be published. Required fields are marked *