Vue通过axios获取数据,渲染的问题

在学习慕课网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;
            })
        },
})
阅读 9.6k
2 个回答

this.productList && this.productList.forEach(function(value){

是productList初始化的问题,应该修改为productList:[],数组才能使用用forEach进行遍历

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题