javascript - Vue.js 无法读取未定义的属性 'split'

标签 javascript vue.js

我在我的 vue.js 应用程序中显示分页符。

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

但我收到错误:

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

但是 message.message 不是空的!我什至收到了预期的结果,为什么会抛出这个错误?

最佳答案

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

因为在某个阶段,它 未定义。显然,如果您最终获得了预期的结果,那么它就会被定义,但那是以后的事情。

您可以通过以下方式解决它:

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

...但最好查看该代码正在做什么的更大画面,并找出为什么 message.message 有时是 undefined 它正在尝试对此进行评估。


作为Bill Criswell指出in a comment ,您可能会考虑使用 computed property在您的模型上而不是模板内表达式。例如:

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

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

然后

v-for="line in messageLines"

关于javascript - Vue.js 无法读取未定义的属性 'split',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40340668/

相关文章:

javascript - querySelector 有效,但 querySelectorAll 无效

Javascript 嵌套函数评估

vue.js - 在自定义组件上使用 v-model

javascript - 让 Vue 更新 View /组件

css - 如何在范围仅限于组件的vue组件中导入CSS文件?

javascript - Open Graph 标签和 Nuxt.js(产品?)的问题

html - list.js javascript 库不工作

javascript - 为什么在 JavaScript 中 while 和 do..while 之间存在巨大的时间差异

javascript - IE7 标准文档模式下的 SPAN/DIV 高度不正确

javascript - Vue.js 将存储数据作为 prop 传递会导致突变警告