在學(xué)習(xí)慕課網(wǎng)vue購物車視頻里,遇到問題,在beforeMount里邊通過axios獲取數(shù)據(jù),然后賦值給data里邊的數(shù)據(jù),在comupted里邊使用forEach遍歷對象,都會出Cannot read property ‘forEach’ of null,這個(gè)錯(cuò)誤。經(jīng)過測試跟猜想,出那個(gè)錯(cuò)誤是因?yàn)橥ㄟ^axios還沒獲取到數(shù)據(jù),就開始遍歷對象,原因可能是因?yàn)閍xios獲取到對象再進(jìn)行其它操作是異步的。如何才不會報(bào)錯(cuò)呢?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; }) },})
Vue通過axios獲取數(shù)據(jù),渲染的問題
慕妹3146593
2018-12-19 17:15:17