在学习慕课网vue购物车视频里,遇到问题,在beforeMount里边通过axios获取数据,然后赋值给data里边的数据,在comupted里边使用forEach遍历对象,都会出Cannot read property ‘forEach’ of null,这个错误。经过测试跟猜想,出那个错误是因为通过axios还没获取到数据,就开始遍历对象,原因可能是因为axios获取到对象再进行其它操作是异步的。如何才不会报错呢?var vm=new Vue({ el:".shopcar", data:{ productList:null }, computed:{ total:function() { var money=0; this.productList.forEach(function(value){ if(value.checked){ money+=value.productPrice*value.productQuentity } }) return money; } }, beforeMount:function() { axios.get("data/cart.json").then((resq)=> { this.productList=resq.data.result.productList; }) },})
添加回答
举报
0/150
提交
取消