1
I’m using Vue.js and I came across the title error.
I have an object with array:
students[
contact: {
mobile: null,
phone: null
}
],
The array contact
is not always filled.
How do I not give TypeError: Cannot read property 'phone' of undefined
when the array has not been created?
I tried to add in more also did not give:
mounted () {
this.students.contact.fone = ''},
but
students
nor is an array...– thxmxx
pasted wrong fit
– user122387
But it’s still wrong... It should be:
[{contact: { mobile: null, phone: null } }]
. And then you access it like this:this.students[0].contact.fone
– thxmxx
At where this array is declared, at date? Makes a methods or a computed to check that the array is filled. If you have filled in do such a thing but do something else.
– LeAndrade
I did so and called no created, but the same error continues: check () { if (!this.students.contact) { this.students.contact.phone = 0 this.students.contact.mobile = 0 } },
– user122387
You’re accessing it wrong yet... It’s a array you want to access, you have to access the property using an index []
– LeAndrade
got it. changed to: check () { if (!this.Students[0].contact) { this.Students[0].contact.phone = 0 this.Students[0].contact.mobile = 0 } }, same error yet
– user122387
Note that the key is "phone" and not "phone".
– Victor Alessander
It would be easier and faster to help you if you set a working example and post editing the question. Preferably a minimal example, with only enough code to reproduce the error.
– fernandosavio
Look at you that example works perfectly. So we need to see more your code to find out where the error is
– fernandosavio