Vue.js中如何保证先完成管理员权限校验再调用用户列表接口
问题根因
getCurrentUser方法未返回Promise实例,导致await this.getCurrentUser()没有实际等待接口返回就结束,校验逻辑的执行时序晚于用户列表请求- 未在校验完成的时序节点主动触发用户列表拉取逻辑,或者原有拉取逻辑的触发时机没有关联校验结果
调整方案
1. 改造getCurrentUser方法,返回Promise
getCurrentUser(){ // 新增return语句,将Common.getUser返回的Promise传递出去 return Common.getUser().then(data => { this.isAdmin = !!data.admin; }); },
2. 调整mounted生命周期逻辑,校验完成后再触发列表拉取
async mounted() { await this.getCurrentUser(); // 校验完成后调用paging方法拉取用户列表 this.paging(1); },
3. 可选优化:给paging方法加权限拦截,防止其他场景提前调用
paging: function (pageNumber) { // 非管理员直接拦截请求 if(!this.isAdmin) return; this.requestParam.page = pageNumber == undefined ? 1 : pageNumber; const param = Common.param(this.requestParam); axios.get('/api/users?' + param).then(function (response) { // 原有列表处理逻辑 }).catch(function (error) { console.log(error.response); }); },
额外注意
如果你的paging方法原本是通过watch监听参数、或者其他生命周期/事件自动触发的,需要给对应的触发逻辑加上isAdmin已完成赋值的判断,避免未校验就提前发起请求。
内容的提问来源于stack exchange,提问作者gippo
相关产品推荐
相关产品推荐

