虽然输出正确。我遇到此错误:无法读取未定义的属性“状态”。我怀疑是因为在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>
如您所料,这是因为listing
从一个空数组开始,此数组稍后会填充。
您的计算出的属性对此不做任何检查,因此this.listing[0]
将undefined
尽早进行。
您只需要在计算的人口中添加一张支票
computed: {
showStatus () {
return this.listing[0]?.status || []
}
}
如果以前没有看到过这种语法,请参见可选链接(?。)。
一种替代方法是listing
使用一些安全的默认数据进行初始化
data: () => ({
listing: [{ status: [] }]
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句