[Vuejs]-How do I prevent the same set of error messages from showing after form submission in Vue.js?

0👍

Easiest method I can think of:

Clear the array every time you fire the button

you can either do it on the template tag

<button 
  type="submit" 
  @click="errors = []"
>

or in the checkForm method

checkForm() {
  this.errors = [] //make sure to place it at the top
}

Mentionables

also, not within your question but you cannot compare array with ===, or even ==, it will always return false

I am referring to this

    if(this.skills === []){
      this.errors.push('Select at least one.');
    }

since you just want to know whether it is empty, use .length instead. But if you want to compare like

[1, 2] == [1, 2]

it will always return false, but you can google up the solution easily as it is very popular issue that JS developers face

0👍

Instead of pussing error messages to array you can use Object or even if you want to stick with error you can use array include function to check if that already in array or not. Like:

if (!this.errors.includes('Staff Name required.');
{
    this.errors.push('Staff Name required.');
}

Or if you want to use Object you can do something like

data() {
   return {
      errors: {
           staf_name: null,
       }

   }
}

then in your code you can update it like this.errors.staf_name = '';

Thanks

Leave a comment