我只想在开始显示“无数据”。当用户选择没有数据的内容时。我使用v-if,但未显示该消息,并添加了一些JavaScript代码,但它根本没有用。如何使用VueJS做到这一点?有人可以帮我解决我的问题吗?这是我的代码
HTML
<div class="wrapper mt-5">
<canvas ref="myChart2" id="myChart2" v-if="myChart2 != 0" width="600" height="250" class="mb-5"></canvas>
<span v-if="myChart2 == 0">No data</span>
</div>
方法
axios.post(this.urlRoot + this.api + "best_beneficiary_reports.php?barangay_id=" + this.filter_search + "&search=" + this.select_reports)
.then(response => {
console.log(response);
vm.best_beneficiaries = response.data
var ctxChart = self.$refs.myChart2.getContext('2d');
for(var i = 0; i < this.best_beneficiaries.length; i++) {
sum += parseFloat(this.best_beneficiaries[i].Total);
}
if (this.myChart2) this.myChart2.destroy();
this.myChart2 = new Chart(ctxChart, {
type: 'pie',
data: {
labels: vm.best_beneficiaries.map(item => item.Beneficiary),
datasets: [{
label: 'Total Amount',
data: vm.best_beneficiaries.map(item => (item.Total / sum * 100).toFixed(2)),
backgroundColor: this.poolColors(vm.best_beneficiaries.length),
borderColor: '#eee',
borderWidth: 2
}]
},
responsive : true,
options: {
title: {
display : true,
text : "Lifetime Best Beneficiary",
fontFamily: "sans-serif",
fontSize: 18,
},
legend: {
display: false
},
tooltips: {
enabled: true,
mode: "single",
callbacks: {
title: function (tooltipItem, data) { return 'Date: ' + data.labels[tooltipItem[0].index]; },
label: function (tooltipItems, data) { return 'Avg: ' + data.datasets[tooltipItems.datasetIndex].data[tooltipItems.index] + "%"; }
},
animation: {
onComplete: function(animation) {
var firstSet = animation.myChart2.config.data.datasets[0].data,
dataSum = firstSet.reduce((accumulator, currentValue) => accumulator + currentValue);
if (typeof firstSet !== "object" || dataSum === 0) {
document.getElementById('no-data').style.display = 'block';
document.getElementById('myChart2').style.display = 'none'
}
}
}
}
}
});
}).catch(e => {
console.log(e)
});
答案 0 :(得分:1)
大概this.myChart2
是在其他地方声明的,将用于访问图表对象,我猜想此属性永远不会是== 0
,因此不是合适的测试条件。
您要查找的属性是数据集中this.myChart2.data.dataset.data.length
中数据数组的长度,不幸的是,该属性在从服务器接收到数据之前一直存在,因此直接引用它会导致'无法读取属性长度未定义的错误
我的建议是在vue组件中初始化另一个属性以存储数据长度,例如this.myChart2Length = 0;
,并在得到axios响应this.myChart2Length = vm.best_beneficiaries.length || 0;
时更新此长度
然后,您可以在模板中以v-if
条件引用新属性
<div class="wrapper mt-5">
<canvas ref="myChart2" id="myChart2" v-if="myChart2Length > 0" width="600" height="250" class="mb-5"></canvas>
<span v-else >No data</span>
</div>