一、存在问题
在vue生命周期中的create中请求接口数据时
<template> <div>{{App.strategys.name}}</div>
</template>
data() { return { App: {},
appName: 'name1', } } created() { if (this.appName) { requset.get(url, this.appName).then((res) => { //调用接口
this.App = res.data;
})
console.log(this.App); //打印出来为空对象
}
},
//接口数据data格式如下
{
app_name: 'name1',
strategys: {
name: 'test',
action: 'action',
}
}
此时会报TypeError错误:TypeError: Cannot read properties of undefined (reading 'name')
二、问题解决
问题中涉及的知识点有两个:
1、对象获取属性
App.strategys.name,此时App的初始值为{},若App无数据,则App.strategys为undefined,但不会报错,而之后取属性name就会变成undefined.name,即报错TypeError。
1、异步与同步问题
在create中调用接口,requset.get(url, this.appName) 为Promise,属于同步任务,但其回调函数then属于异步任务(中的微任务),此时为App的赋值操作被放到任务队列中执行,待执行完毕后返回,但此时代码会继续往下执行打印App,由于赋值操作尚未执行完毕,此时结果为空对象。而在vue中created之后会对页面模版template进行渲染,在页面渲染中存在App.strategys.name,从而报错。
解决办法
方法一、在调用接口时使用async,await等待接口返回后继续执行。
async created() { if (this.appName) { const {data} = await requset.get(url, this.appName) //调用接口 this.App = data; console.log(this.App); //打印出来为空对象 } },
方法二、为模版设置状态,控制页面渲染
<template> <div v-if="isEmptyObject(App)">{{App.strategys.name}}</div> </template>
//若app为空则不会渲染