How to evaluate max length of a text area using vuejs computed property?

Tags: , ,



I have a text area in a form that I am using to write the description of something. But, the max char limit is 5. I am trying to calculate the max length of my description using the computed property. But, somehow the computed property is not firing when the length of the description crosses the limit of 5 chars. Following is my simple code.

  props: {
    infoData: {
      type: Object,
      default: () => {
        return {
          category: "",
          side_categories: "",
          description: "",
          commentValidationState: null
        };
      }
    },
  },
  computed: {
    descriptionValidation(){
      if(this.infoData.description?.length > 5){
        alert("Max length exceeded!");
      }
    }
  }

It is noted that I am using the prop directly in the computed property.

My HTML:

  <b-form-group
          class="col-md-12"
          label="Beschreibung"
          label-for="description"
          invalid-feedback="maximal 750 Zeichen"
          :state="infoData.commentValidationState"
      >
        <b-textarea
            class="form-control"
            name="description"
            id="description"
            v-model="infoData.description"
        />
      </b-form-group>

Answer

Computed properties must return the result of some computation. Here, a watcher would be more appropriate. In this case, the value to watch would be the length of this.infoData.description. Consequently, I would first use a computed property to get the length of this.infoData.description and then use a watcher to monitor its value.

Here is my implementation:

<template>
  <div>
      <!--- Component HTML -->
   </div>
</template>

<script>
export default {
  props: {
    infoData: {
      type: Object,
      default: () => {
        return {
          category: "",
          side_categories: "",
          description: "",
          commentValidationState: null
        };
      }
    },
  },
  watch: {
    descriptionLength(new_value){
      if(new_value> 5){
        alert("Max length exceeded!");
      }
    }
  },
  computed: {
    descriptionLength(){
      return this.infoData.description?.length
    }
  }
}
</script>

And here is its parent:

<template>
  <div>
    <textarea v-model="infoData.description" />
    <MyComponent :infoData="infoData" />
  </div>
</template>

<script>
import MyComponent from '@/components/MyComponent.vue'
export default {
  components: {
    MyComponent,
  },
  data() {
    return {
      infoData: {
          category: "",
          side_categories: "",
          description: "",
          commentValidationState: null
      }
    }
  },
}
</script>



Source: stackoverflow