TypeError: Cannot read property 'split' of undefined

最近跟着慕课网学一个电商项目,学习前端页面出现了如下错误提示:



后面后台管理页面也出现了类似问题:


解决的办法即增加未定义(空字符串)的情况:





以下引用自:https://stackoverflow.com/questions/40340668/vue-js-cannot-read-property-split-of-undefined

ccepted

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.


As Bill Criswell points out in a comment, you might look at using a computed property on your model for that rather than an in-template expression. E.g.:

var vm = new Vue({
    // ...your other stuff here...

    // Computed properties:
    computed: {
        messageLines: function() {
            return (this.message.message || "").split("\n");
        }
    }
});

then

v-for="line in messageLines"

猜你喜欢

转载自blog.csdn.net/tfstone/article/details/80270327