在學習慕課網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; }) },})
Vue通過axios獲取數據,渲染的問題
慕妹3146593
2018-12-19 17:15:17