Vue.js中如何每0.5秒动态新增加载组件TheLoadingLine?
实现逐秒新增加载组件的方案
核心思路是用响应式数组控制渲染数量,配合setInterval定时更新数组,同时记得在API请求结束后清理定时器,避免内存泄漏。
具体实现步骤:
父组件中定义响应式数据
用一个数组记录要渲染的加载组件数量,初始值放一个元素(对应初始显示1条),再定义变量存储定时器实例,方便后续清除。编写定时添加逻辑
写一个方法启动定时器,每隔500ms往数组里追加一个元素(元素内容无所谓,数组长度就是显示的组件数)。控制定时器生命周期
- 在API请求发起前调用启动方法,开始加载动画
- API请求完成(成功/失败)时,立刻清除定时器,避免继续新增组件
完整代码示例(Vue3 Composition API)
<template> <div class="loading-container"> <!-- 循环渲染加载组件 --> <TheLoadingLine v-for="(item, index) in loadingLines" :key="index" /> </div> </template> <script setup> import { ref, onMounted, onUnmounted } from 'vue' import TheLoadingLine from './TheLoadingLine.vue' // 控制加载组件数量的数组,初始显示1条 const loadingLines = ref([1]) // 存储定时器实例,方便后续清除 let loadingTimer = null // 启动定时新增逻辑 const startLoading = () => { // 先清除已有定时器,避免重复启动 if (loadingTimer) clearInterval(loadingTimer) loadingTimer = setInterval(() => { // 每次往数组加一个任意值,触发渲染新增组件 loadingLines.value.push(loadingLines.value.length + 1) }, 500) } // 停止加载逻辑(API请求完成时调用) const stopLoading = () => { if (loadingTimer) { clearInterval(loadingTimer) loadingTimer = null // 可选:如果需要加载完成后清空加载组件,就清空数组 // loadingLines.value = [] } } // 组件卸载时确保清除定时器,防止内存泄漏 onUnmounted(() => { stopLoading() }) // 示例:模拟API请求 const fetchData = async () => { // 开始加载 startLoading() try { // 替换成你的实际API请求 const res = await fetch('https://your-api-url.com/data') const data = await res.json() // 请求成功后停止加载 stopLoading() // 处理返回的数据... } catch (err) { // 请求失败也停止加载 stopLoading() console.error('请求失败:', err) } } // 页面挂载时发起请求(根据业务场景调整触发时机) onMounted(() => { fetchData() }) </script>
Vue2 Options API 写法参考
如果是Vue2项目,逻辑类似,仅语法调整:
<template> <div class="loading-container"> <TheLoadingLine v-for="(item, index) in loadingLines" :key="index" /> </div> </template> <script> import TheLoadingLine from './TheLoadingLine.vue' export default { components: { TheLoadingLine }, data() { return { loadingLines: [1], loadingTimer: null } }, methods: { startLoading() { if (this.loadingTimer) clearInterval(this.loadingTimer) this.loadingTimer = setInterval(() => { this.loadingLines.push(this.loadingLines.length + 1) }, 500) }, stopLoading() { if (this.loadingTimer) { clearInterval(this.loadingTimer) this.loadingTimer = null // this.loadingLines = [] // 可选清空加载组件 } }, async fetchData() { this.startLoading() try { const res = await fetch('https://your-api-url.com/data') const data = await res.json() this.stopLoading() // 处理数据 } catch (err) { this.stopLoading() console.error(err) } } }, mounted() { this.fetchData() }, beforeDestroy() { this.stopLoading() } } </script>
注意事项
- 必须在组件卸载、请求完成时清除定时器,否则会导致内存泄漏
- 如果需要限制最大加载条数,可以在
setInterval里加判断,比如if (loadingLines.value.length >= 5) clearInterval(loadingTimer),避免无限新增组件
内容的提问来源于stack exchange,提问作者thiebo
相关产品推荐
相关产品推荐

