【问题标题】:VueJS - Cannot read property 'status' of undefinedVueJS - 无法读取未定义的属性“状态”
【发布时间】:2020-11-05 14:02:33
【问题描述】:

虽然输出是正确的。我有这个错误:无法读取未定义的属性“状态”。我怀疑这是因为在 ajax 调用之后添加了列表。我该如何改进?

<template v-for="status in showStatus">
    <div class="col-sm-1">{{status}}</div>
</template>

<script>
    var app = new Vue({
        el: "#app",
        data: { 
            listing: []
        },
        created: function(){
            axios.get('/getListing')
            .then(function (response) {
                app.listing = response.data;
            })
            .catch(function (error) {
                console.log(error);
            });
        },
        computed: {
            showStatus(){
                return this.listing[0].status;
            }
        }
    });
</script>

【问题讨论】:

  • &lt;template&gt; 是您组件的根模板吗?

标签: vue.js axios


【解决方案1】:

正如您所猜测的,这是因为listing 开始时是一个空数组,稍后会填充。

您的计算属性不会对此进行任何检查,this.listing[0] 将在早期为 undefined

你只需要在你的计算属性中添加一个检查

computed: {
  showStatus () {
    return this.listing[0]?.status || []
  }
}

如果您以前没有见过这种语法,请参阅 Optional chaining (?.)


另一种方法是使用一些安全的默认数据初始化listing

data: () => ({
  listing: [{ status: [] }]
})

【讨论】:

    猜你喜欢
    • 2019-06-08
    • 2021-11-28
    • 2019-07-25
    • 2021-07-07
    • 2020-11-10
    • 1970-01-01
    • 2021-11-18
    相关资源
    最近更新 更多