Vue 2.7.10数据渲染延迟与异步函数执行顺序问题求助
Vue 2.7.10 问题解决方案
一、优化v-for渲染速度
针对调用getDetails后v-for渲染延迟的问题,可通过以下方式优化:
- 为v-for添加唯一key
Vue依赖key值识别DOM元素的唯一性,缺少key会导致DOM更新效率低下,添加后能大幅提升渲染速度。修改HTML代码:
<div id="app"> <p v-for="item in userDetails" :key="item.id">{{ item }} is displayed</p> <button @click="anotherFunction()">Click Me!</button> </div>
注意:若数据无业务唯一标识,可临时使用index作为key,但优先推荐业务唯一ID,避免DOM复用异常。
- 优化数组更新方式
虽然push属于Vue响应式数组支持的方法,但如果是批量数据更新,可先构建临时数组再整体赋值,减少响应式触发次数:
// 在getDetails的then回调中修改 const tempArr = [...this.userDetails, result[0]] this.userDetails = tempArr
- 大数据量场景用虚拟滚动
如果userDetails包含成百上千条数据,普通v-for会渲染全部DOM节点导致卡顿,可采用虚拟滚动方案,仅渲染可视区域内的DOM节点,大幅降低渲染压力。
二、让anotherFunction等待异步请求完成
当前getDetails未返回Promise,无法追踪异步请求的完成状态,修改步骤如下:
- 让getDetails返回Promise
修改getDetails函数,返回axios请求的Promise,以便调用方追踪异步状态:
methods: { getDetails(actionType, idUser) { // 需补充定义username变量,否则会报错 return axios.post("https://example.com/link", { Username: username }).then(response => { const result = response.data; this.userDetails.push(result[0]) return result[0] // 可选:返回获取到的数据,方便后续使用 }).catch(error => { this.showError('Error', 4000); console.error('Error:' + error); throw error; // 抛出错误,让调用方可以捕获 }); }, // 使用async/await等待请求完成 async anotherFunction() { await this.getDetails('multiple', '1') // 此时请求已完成,userDetails已更新 console.log(this.userDetails); } }
- 修复组件代码结构问题
原代码存在规范错误:data必须是函数(Vue 2组件要求),getDetails和anotherFunction需放在methods选项中,完整修正后的组件代码:
<script> export default { name: 'App', data() { return { userDetails: [] } }, methods: { getDetails(actionType, idUser) { const username = 'xxx'; // 补充定义username变量 return axios.post("https://example.com/link", { Username: username }).then(response => { const result = response.data; this.userDetails.push(result[0]) }).catch(error => { this.showError('Error', 4000); console.error('Error:' + error); throw error; }); }, async anotherFunction() { await this.getDetails('multiple', '1') console.log(this.userDetails); }, showError(msg, duration) { // 补充实现showError函数逻辑 console.log(msg); } } } </script>
内容的提问来源于stack exchange,提问作者user9172014
相关产品推荐
相关产品推荐

