首页 > 解决方案 > VueJS [Vue 警告] 渲染错误“TypeError”无法读取未定义的属性“PRICE”

问题描述

我正在尝试从 customerProduct 数据对象计算总账单(所有产品*使用量的总和)并显示账单金额。我正在调用计算方法来执行此操作。customerProduct 数据是从方法中的getapi 调用中获取的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
}

标签: vue.js

解决方案


这是一个更新的代码。试一次。

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>


推荐阅读