Vue.js中如何同时运行两个函数?解决执行阻塞问题
解决Vue.js中定时函数被点击事件阻塞的问题
问题原因
JavaScript是单线程运行环境,所有同步任务都会占用主线程执行。如果handleFileUpload中包含同步耗时操作(比如大量数据计算、同步IO),会阻塞主线程,导致setInterval的回调函数(getUploadedStatus)无法被及时触发,必须等同步操作完成后才能继续执行。
解决方案
- 确保异步操作不阻塞主线程:将耗时的同步逻辑包装为异步任务,让主线程能及时处理定时器回调。
- 避免定时器重复请求:给定时任务加锁,防止上一次请求未完成时发起新请求,减少资源占用。
修改后的代码
<template> <div> <select v-model="file_id" class="form-control"> <option v-for="(file, index) in files" :value="file.value" :key="index"> {{ file.label }} </option> </select> <button class="btn btn-success" @click="handleFileUpload">Import</button> </div> </template> <script> import axios from 'axios'; export default { data() { return { files: [], file_id: '', // 补充模板中用到的v-model变量 isCheckingStatus: false, // 标记状态请求是否在进行中 upload_status: null // 定时器实例 }; }, mounted() { this.upload_status = setInterval(() => { this.getUploadedStatus(); }, 10000); // 修正为需求中的10秒 }, methods: { async handleFileUpload() { // 将上传逻辑放入异步队列,不阻塞主线程 await new Promise(resolve => { setTimeout(async () => { try { const response = await axios.post('/your-upload-api', { file_id: this.file_id // 其他请求参数 }); // 处理上传响应逻辑 console.log('上传完成:', response.data); } catch (error) { console.error('上传失败:', error); } finally { resolve(); } }, 0); }); }, async getUploadedStatus() { // 避免重复发起状态请求 if (this.isCheckingStatus) return; this.isCheckingStatus = true; try { const response = await axios.get('/your-status-api', { params: { file_id: this.file_id } }); // 处理状态更新逻辑 console.log('当前上传状态:', response.data); } catch (error) { console.error('获取状态失败:', error); } finally { this.isCheckingStatus = false; } } }, beforeDestroy() { if (this.upload_status) { clearInterval(this.upload_status); this.upload_status = null; } } }; </script>
关键说明
- 用
setTimeout(..., 0)将上传逻辑放入异步任务队列,让主线程优先处理定时器回调等其他任务。 - 给
getUploadedStatus添加isCheckingStatus锁,避免同一时间多次发起状态请求,防止不必要的资源消耗。 - 使用
async/await让异步代码逻辑更清晰,同时保证错误能被捕获处理。
内容的提问来源于stack exchange,提问作者matheen ulla
相关产品推荐
相关产品推荐

