vue.js - VueJS [Vue 警告] 渲染错误“TypeError”无法读取未定义的属性“PRICE”
问题描述
我正在尝试从 customerProduct 数据对象计算总账单(所有产品*使用量的总和)并显示账单金额。我正在调用计算方法来执行此操作。customerProduct 数据是从方法中的get
api 调用中获取的created()
。
问题:在初始渲染中,控制台显示以下错误:[Vue warn]: Error in render: "TypeError: Cannot read property 'PRICE' of undefined"
. 这是因为计算需要一些时间,同时当模板 html 代码呈现时,customerProductData 没有正确获取?另外,可以在这里使用watch
属性帮助吗?
计算总账单的计算方法:
computed:{
billAmount(){
var billAmountWithoutDiscount = 0;
if(typeof(this.customerProductData[0].PRICE) == undefined){
return 0.0
}
else{
for(let i=0;i<this.customerProductData.length;i++){
billAmountWithoutDiscount += this.customerProductData[i].PRICE * this.customerProductData[i].USAGE;
}
return Number((100.0 - this.customerMetaData.discount)*billAmountWithoutDiscount/100).toLocaleString();
}
}
}
获取 API 调用:
methods:{
async init(){
const response = await axios.get("/subscribe/getPresalesPricingMetaData/"+this.customerName)
this.customerProductData = response.data;
// console.log(response.data)
this.getCustomerMetaData();
},
}
客户产品对象:
customerProductData:[
0: {
'PRICE': 10,
'USAGE': 2000
},
1: {
'PRICE': 30,
'USAGE': 230
},
2: {
'PRICE': 50,
'USAGE': 200
},
3: {
'PRICE': 30,
'USAGE': 1000
},
]
折扣值:
customerMetaData:{
'discount': 2.2
}
解决方案
这是一个更新的代码。试一次。
new Vue({
el: '#app',
data: {
message: "sample mesage",
customerProductData:[
{
'PRICE': 10,
'USAGE': 2000,
'CONSUMPTION': 100
},
{
'PRICE': 30,
'USAGE': 230,
'CONSUMPTION': 200
},
{
'PRICE': 50,
'USAGE': 200,
'CONSUMPTION': 300
},
{
'PRICE': 30,
'USAGE': 1000,
'CONSUMPTION': 400
},
],
customerMetaData: {
'discount': 2.2
}
},
computed: {
billAmount(){
let billAmountWithoutDiscount = 0;
if(typeof(this.customerProductData[0].PRICE) == undefined){
return 0.0
} else {
for(let i=0;i<this.customerProductData.length;i++){
billAmountWithoutDiscount += this.customerProductData[i].PRICE * this.customerProductData[i].CONSUMPTION;
}
return Number((100.0 - this.customerMetaData.discount) * billAmountWithoutDiscount / 100).toLocaleString();
}
}
},
methods:{
async init(){
let that = this;
axios.get("/subscribe/getPresalesPricingMetaData/"+this.customerName).then(function(response){
that.customerProductData = response.data;
that.getCustomerMetaData();
})
},
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<h1>{{ billAmount }}</h1>
</div>
推荐阅读
- pyspark - 遍历 pyspark 数据帧以查找分层血统
- django - 如何在考试服务器上的 Apache 服务器上运行我的 Django 项目?
- angular - 有没有办法在使用 observables 时将复杂的 json 数据映射到 typescript 中的接口?
- html - 需要 CSS 帮助 - 通过媒体查询阻止布局变化 - flex?
- java - 如何使用 radioButton 通过用户输入执行不同的方程式?
- asp.net - Azure Web 应用找不到连接字符串
- html - 在 Firefox 上放大或缩小后,单选按钮正在改变大小
- c# - ASP.NET ExceptionMiddleware 不继续代码块
- dependency-injection - 在 QuarkusTest 中如何在某些情况下使用模拟,但在其他情况下不使用?
- azure - 如何读取自定义配置设置?