vue-star-rating TypeError:无法读取 listToStyles.js:26 中未定义的属性“length”
2020-06-09
64
在 Vue 中调用 getRating 函数时出现此错误。我在 laravel 中使用 Vue-star-rating 包。不明白问题是什么。
getRating(){
var pathArray = location.pathname.split('/');
var pid = pathArray[2];
fetch(`/api/rating/${pid}`)
.then(res => res.json())
.then(res => {
var mydata = res.data;
this.totaluser = mydata.length;
var sum = 0;
for(var i=0; i < mydata.length; i++){
sum += parseFloat(mydata[i]['rating']);
}
var avg = sum/mydata.length;
this.totalrate = parseFloat(avg.toFixed(1));
var bar1 = 0;
var bar2 = 0;
var bar3 = 0;
var bar4 = 0;
var bar5 = 0;
for(var j = 0; j < mydata.length; j++){
if(parseInt(mydata[j]['rating']) == '1'){
bar1 += 1;
}
if(parseInt(mydata[j]['rating']) == '2'){
bar2 += 1;
}
if(parseInt(mydata[j]['rating']) == '3'){
bar3 += 1;
}
if(parseInt(mydata[j]['rating']) == '4'){
bar4 += 1;
}
if(parseInt(mydata[j]['rating']) == '5'){
bar5 += 1;
}
}
$('.bar-1').css('width', bar1+'%');
$('.bar-2').css('width', bar2+'%');
$('.bar-3').css('width', bar3+'%');
$('.bar-4').css('width', bar4+'%');
$('.bar-5').css('width', bar5+'%');
})
.catch(err => {
console.log(err)
});
},
TypeError:无法读取 listToStyles.js:26 中未定义的属性“length”
希望大家给我一些建议!
2个回答
您所做的所有“长度”操作都在您获取的 res.data 上,并且看起来那个是未定义的。尝试制作一个控制台日志,并确保您的 api 为您提供了您想要的 res.data.length
ryuzeke
2020-06-09
您的
myData
未定义。
您可以编写更安全的代码,如下所示
getRating(){
var pathArray = location.pathname.split('/');
var pid = pathArray[2];
fetch(`/api/rating/${pid}`)
.then(res => res.json())
.then(res => {
var mydata = res.data || []; // sets myData to empty array if res.data is undefined
this.totaluser = mydata.length;
var sum = 0;
for(var i=0; i < mydata.length; i++){
sum += parseFloat(mydata[i]['rating']);
}
var avg = sum/mydata.length; // this will produce error if mydata.length is zero
this.totalrate = parseFloat(avg.toFixed(1));
var bar1 = 0;
var bar2 = 0;
var bar3 = 0;
var bar4 = 0;
var bar5 = 0;
for(var j = 0; j < mydata.length; j++){
if(parseInt(mydata[j]['rating']) == '1'){
bar1 += 1;
}
if(parseInt(mydata[j]['rating']) == '2'){
bar2 += 1;
}
if(parseInt(mydata[j]['rating']) == '3'){
bar3 += 1;
}
if(parseInt(mydata[j]['rating']) == '4'){
bar4 += 1;
}
if(parseInt(mydata[j]['rating']) == '5'){
bar5 += 1;
}
}
$('.bar-1').css('width', bar1+'%');
$('.bar-2').css('width', bar2+'%');
$('.bar-3').css('width', bar3+'%');
$('.bar-4').css('width', bar4+'%');
$('.bar-5').css('width', bar5+'%');
})
.catch(err => {
console.log(err)
});
},
s4k1b
2020-06-09