当后端返回的数据格式出问题时:
本来res.data应该是个对象,然后某次出现了字符串
JSON.parse转换还失败:
一看对象的某个键的值为NaN(其实是数据的问题),导致返回值不是合法的json格式;
然后就进行了粗鲁的处理:
res=>{ if(typeof res.data!=='string'){ if(res.data.code==='200'){ this.tableDataAll=res.data.result.concat() this.tableData=this.tableDataAll.slice(0,this.pageSize) this.total=this.tableDataAll.length this.loading=false }else{ this.loading=false this.$message({ message:'数据加载失败!', type:'error', duration: 2000, }); } }else { let origStr=res.data let replaceStr=origStr.replace(/NaN/g,"-") // console.log('转码',replaceStr) let trueDate =JSON.parse(replaceStr) // console.log('trueDate',trueDate) if(trueDate.code==='200'){ // this.total=res.data.result['total_num'] this.tableDataAll=trueDate.result.concat() this.tableData=this.tableDataAll.slice(0,this.pageSize) this.total=this.tableDataAll.length this.loading=false }else{ this.loading=false this.$message({ message:'数据加载失败!', type:'error', duration: 2000, }); } }
精简一下:
if(typeof res.data==='string'){ let replaceStr=res.data.replace(/NaN/g,"-") // console.log('转码',replaceStr) res.data =JSON.parse(replaceStr) } if(res.data.code==='200'){ this.tableDataAll=res.data.result.concat() this.tableData=this.tableDataAll.slice(0,this.pageSize) this.total=this.tableDataAll.length this.loading=false }else{ this.loading=false this.$message({ message:'数据加载失败!', type:'error', duration: 2000, }); }