Vue中if条件内teamsList对象为空,权限判断逻辑失效求助
问题解决:异步加载导致权限判断不生效
你的问题核心是异步代码的执行顺序问题。loadTeams()是异步请求,它的.then()回调要等请求完成后才会执行,但你写的权限判断代码是同步执行的——在loadTeams()发起请求后立刻就跑了,这时候this.teamsList还没被赋值,自然是空的,判断条件也就没法生效。
给你两种可行的修改方案:
方案一:把权限判断移到.then回调里
async created() { console.log('teams list is before loading teams', this.teamsList); this.loadTeams() .then((response) => { this.teamsList = response.data; console.log('teams list is after loadteams', this.teamsList); // 权限判断移到这里,确保teamsList已经获取到数据 if (this.teamsList.teamName === 'admins') { this.haveAccess = true; console.log('access-check', this.teamsList.teamName); } console.log('access-check', this.haveAccess, this.teamsList); }) .catch((error) => { console.log(error); }); }
方案二:用async/await简化异步逻辑
因为你已经给created加了async关键字,直接用await让异步代码看起来像同步的,逻辑更清晰:
async created() { console.log('teams list is before loading teams', this.teamsList); try { const response = await this.loadTeams(); this.teamsList = response.data; console.log('teams list is after loadteams', this.teamsList); if (this.teamsList.teamName === 'admins') { this.haveAccess = true; console.log('access-check', this.teamsList.teamName); } console.log('access-check', this.haveAccess, this.teamsList); } catch (error) { console.log(error); } }
这两种方式都是确保权限判断在异步请求完成、teamsList被赋值之后才执行,这样就能正确读取到this.teamsList的内容,让权限判断生效。
内容的提问来源于stack exchange,提问作者Mr. A
相关产品推荐
相关产品推荐

