Vue.js中Promise请求执行时显示元素、完成后隐藏的实现方案问询
嘿,搞定Vue请求时的加载状态控制!
要实现「请求过程中显示加载动画,请求完成后隐藏」的效果,其实只需要加个状态变量来控制元素的显示/隐藏,再在请求的生命周期里更新这个状态就行啦。下面是具体的修改步骤:
1. 给Vue加个加载状态标记
在data里新增一个布尔值变量,用来标记当前是不是在加载中:
data: { food:[], isLoading: true // 一开始设为true,因为页面刚加载就会发起请求 },
2. 在请求过程中切换状态
修改getCode方法,用try...finally包裹请求逻辑——不管请求成功还是失败,最后都会把加载状态关掉,避免请求失败后加载动画一直转:
async getCode() { this.isLoading = true; // 请求开始,打开加载状态 try { this.food = await Promise.all(this.food.map(async food => { food.box = await this.request('GET',`https://example.com/${food.Identifier}/content/voc`) return food })) } catch (error) { // 这里可以加错误处理,比如给用户弹个提示,或者打个日志 console.error('请求出问题啦:', error); } finally { this.isLoading = false; // 请求完了,不管成功失败都关掉加载 } },
另外注意哦,你原来的request方法里,jQuery的ajax错误回调是error不是fail,我已经帮你修正了,不然请求失败的时候不会触发reject,加载状态会一直停在true~
3. 把状态绑定到加载元素上
在HTML里用Vue的v-if指令来控制加载动画的显示,只有isLoading为true的时候才显示:
<div id="app"> <div id="spin" v-if="isLoading"></div> <!-- 请求完成后可以显示你的内容,比如渲染food列表 --> <div v-if="!isLoading"> <p>加载完成!一共拿到了{{ food.length }}条数据</p> <ul> <li v-for="item in food" :key="item.Identifier">{{ item.Identifier }}</li> </ul> </div> </div>
完整的修改后代码
JavaScript
new Vue({ el: "#app", data: { food:[], isLoading: true }, mounted:function(){ this.getCode(); }, methods: { async getCode() { this.isLoading = true; try { // 小提醒:如果你的初始food数组是空的,Promise.all不会执行任何请求,加载状态会立刻关掉 // 所以要确保调用getCode之前,food已经有需要处理的数据哦 this.food = await Promise.all(this.food.map(async food => { food.box = await this.request('GET',`https://example.com/${food.Identifier}/content/voc`) return food })) } catch (error) { console.error('请求失败:', error); } finally { this.isLoading = false; } }, request(type, url) { return new Promise((resolve, reject) => { $.ajax({ url, type, headers: { accept: "application/json;odata=verbose" }, success: resolve, error: reject // 修正:jQuery ajax错误回调是error不是fail }) }) }, } })
CSS(和原来一致)
#spin { border: 20px solid yellow; border-top: 20px solid; border-radius: 50%; width: 20px; height: 20px; animation: spin 2s linear infinite; margin: auto; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <h2>Promise:</h2> <div id="app"> <div id="spin" v-if="isLoading"></div> <div v-if="!isLoading"> <p>加载完成!共{{ food.length }}条数据</p> <!-- 这里可以根据你的需求渲染具体内容 --> </div> </div>
小提醒
如果你的初始food数组是空的,Promise.all会直接返回空数组,加载状态会立刻变为false,所以要确保在调用getCode之前,food已经有需要处理的数据(比如从其他接口获取,或者本地预设一些数据)。
内容的提问来源于stack exchange,提问作者Vzupo
相关产品推荐
相关产品推荐

