Using computed with dynamic objects in Vue JS

Viewed 304

Hey gang

Since I'm kind of new to Vue JS, I've managed to almost complete a simple staged form project, I'm having trouble with a dynamic object

Assuming that this is the last stage of the form:

<template v-if="currentStage === 3">
  <h2>Step 3 - Additional Params</h2>
  <h3>Please fill all the parameters needed</h3>
  <div v-for="(param, key, index) in params" :key="key">
    <label class="inputLabel" :for="key">Please fill in {{ key }} param</label> <span class="redStar">*</span>
    <input v-model="params[key]" :id="key">
    <span v-if="submitted && $v.params[key] && !$v.params[key].required" class="invalid-feedback">It's a required field, please fill it</span>
    <!--        <span v-if="v$.params[key].$errors[0]" class="invalid-feedback"> {{ v$.params[key].$errors[0].$message }} </span>-->
  </div>
  <button @click="updateStage(0)">Previous</button>
  <button @click="handleLastSubmit">Create</button>
</template>

Inside Data() I created an empty object destined to be fulfilled based on user input from certain field in the form, as suggested in the comment below:

 params() {
      if (this.jsonS.hasOwnProperty(this.tDetails.platform)) {
        for (const [key, value] of Object.entries(this.jsonS[this.tDetails.platform])) {
          this.params[key] = value;
        }
      }
      return this.params;
    },

I tried to add { required } based on vue forums suggestions like this(inside computed):

addRequiredValidation() {
      //Here I need somehow to add validations to params Object.
      for (const key in this.integrationParams) {
          this.$options.validations().integrationParams[key].required = required
         }
      }

And implement it in the validations as follows:

validations() {
  return {
    integrationParams: this.addRequiredValidation,
    trafficDetails: {
      brand: {required, minLength: minLength(3)},
      platform: {required, minLength: minLength(3)},
      whitelabel: {required, minLength: minLength(3)},
      country: {required, minLength: minLength(2)},
      campaignName: {required, minLength: minLength(2)}
    }
  }
},

Ending up getting this error:

TypeError: Cannot convert undefined or null to object at Function.keys ()

1 Answers

You could use another computed field to get your params.

computed: {
  params() {
      const params = {};
      if (this.jsonS.hasOwnProperty(this.tDetails.platform)) {
        for (const [key, value] of Object.entries(this.jsonS[this.tDetails.platform])) {
          params[key] = value;
        }
      }
      return params;
    }
}

The params should be recalculated whenever this.tDetails.platform changes (i.e., a user inputs another platform) and your addRequired property should update correctly.

Related