Jamie Jamie - 1 month ago 29
Javascript Question

Vue.js Cannot read property 'split' of undefined

I'm showing page breaks within my

vue.js
application.

<div class="Message__body__message">
<p v-for="line in message.message.split('\n')" track-by="$index">{{ line }}<br></p>
</div>


But I receive the error:

main.js:7382 [Vue warn]: Error when evaluating expression "message.message.split('\n')": TypeError: Cannot read property 'split' of undefined


But
message.message
is not empty! I even receive the expected result, so why does it throw this error?

Answer

I even receive the expected result, so why does it throw this error?

Because at some stage, it is undefined. Clearly, if you're ultimately getting the result you expect, it's then becoming defined, but that's later.

You could work around it by doing:

v-for="line in (message.message || "").split('\n')"

...but it would probably be better to look at the greater picture of what that code's doing and find out why message.message is undefined at times it's trying to evaluate that.