[Vuejs]-Push data in vuejs data array .push is not a function

0đź‘Ť

The short answer is you need to initialize the errorMessages property in the following way…

data() {
     return {
      errorMessages: []
     };
},

The explanation…

Firstly, when you do the following…

data() {
 return {
  errorMessages: Array
 };
},

this.errorMessages is now a reference to the actual Array class and is not an instance of an array. This is why it says the push method doesn’t exist. This should be more obvious if you log it’s value to the console.

Secondly, when you do the following…

this.errorMessage = { ...message[msg] };

A few things are going wrong. In JavaScript and many other languages, Strings can be treated (to some extent) like an array of characters. For example, if you take a string and access an index (e.g. str[0]) you will receive the character at that position. If you take this idea apply it to how the spread operator works, you are essentially taking all of the elements from an “Array” (in our case a string) and spreading them into an object.

Arrays in JavaScript at their core, are also just objects that have numeric property names (indexes) with some additional built in functionality. So when you spread your string value (message[msg]), it will take each “element” (each character in the string) and create a property in the target object (errorMessages), where the property name is the corresponding index and the value is the character. Which is why you get the following when you log it to the console…

{
  0: 't',
  1: 'h',
  2: 'i',
  3: 's',
  4: 'o',
  5: 'n',
  6: 'e',
}

To take this one step further if you create the following array const myArray = ['a', 'b', 'c'] and then create the following object… const myObject = { ...myArray }; you will see a similar result if you log myObject to the console.

Hope that helps!

Leave a comment