问题:
开发过程中,我们可能会取接口返回的数组数据的第一项,进行页面渲染。当某一用户的该数据为空时,就会出现未定义的报错。
如下:
<script> export default { data() { return { dealItem:{} }; }, methods:{ getPersonInfo(){ this.sendRequest({ // 获取待办数据 url : `flow/act/flowTask/qureyHandleTasks`, method : "GET", data : { userId:userId, taskName:'入库', processDefinitionId:'sample:1:35016' }, hideLoading : true, success: (res) => { if(res.code === 0){ this.dealItem = res.data.datas[0] this.judgeState() } } }) }, judgeState(){ if(this.dealItem.progress === 100){ this.state = true this.dealItem.stateContent = '已通过' }else{ this.state = false this.dealItem.stateContent = '待通过' } } }, beforeMount(){ this.getPersonInfo() } } </script>
报错:
解决:
1.给定默认值;
2.判断是否为空,为空时使用给定的默认值;
<script> export default { data() { return { dealItem:{ sampleName: "无待办", stateContent: "无待办", progress:100, taskName: "无待办" } }; }, methods:{ getPersonInfo(){ this.sendRequest({ // 获取待办数据 url : `flow/act/flowTask/qureyHandleTasks`, method : "GET", data : { userId:userId, taskName:'入库', processDefinitionId:'sample:1:35016' }, hideLoading : true, success: (res) => { if(res.code === 0){ if(res.data.datas.length === 0){ return }else{ this.dealItem = res.data.datas[0] this.judgeState() } } } }) }, judgeState(){ if(this.dealItem.progress === 100){ this.state = true this.dealItem.stateContent = '已通过' }else{ this.state = false this.dealItem.stateContent = '待通过' } } }, beforeMount(){ this.getPersonInfo() } } </script>