文章目录
- 前言
- 一、问题演示
- 二、使用步骤
- 1.One组件
- 2.Two组件
- 封装工具函数处理请求
- 总结
前言
在开发过程中,重复请求发送问题可能会导致数据不一致、服务器压力增加或用户操作异常。以下是解决重复请求问题的常见方法和最佳实践:
一、问题演示
我们看着两个数据都是一样的,都是通过发送请求获取的,我们怎么才能只发一次呢?
二、使用步骤
1.One组件
代码如下(示例):
<template>
<ul>
<li v-for="item in list" :key="item.id">{{ item.name }}-{{ item.age }}--{{ item.email }}</li>
</ul>
</template>
<script setup>
import { ref } from 'vue'
import { getData } from '@/utils/loadData'
const list = ref([])
// 获取数据
getData(1).then((res) => {
list.value = res
})
</script>
<style lang="scss" scoped></style>
2.Two组件
代码如下(示例):
<template>
<ul>
<li v-for="item in list" :key="item.id">{{ item.name }}-{{ item.age }}--{{ item.email }}</li>
</ul>
</template>
<script setup>
import { ref } from 'vue'
import { getData } from '@/utils/loadData'
const list = ref([])
// 获取数据
getData(2).then((res) => {
list.value = res
})
</script>
<style lang="scss" scoped></style>
封装工具函数处理请求
解决思路:就是通过isLoading的状态去做判断。如果发现已经发送了一次请求,下一次在发送就直接得到上一次的返回结果进行返回。
import axios from 'axios'
export const loadData = (id: number) => {
return axios
.get('/src/json/data.json', {
params: { id }
})
.then((res) => {
return res.data
})
}
export const asyncFun = (cb: (...args: any[]) => Promise<any>) => {
const map: Record<string, any> = {}
return (...args: any[]) => {
return new Promise((resolve, reject) => {
const key = JSON.stringify(args)
console.log('Request started for key:', key, 'Current map:', map)
if (!map[key]) {
map[key] = {
resolve: [],
reject: [],
isLoading: false
}
}
const stock = map[key]
stock.resolve.push(resolve)
stock.reject.push(reject)
if (stock.isLoading) {
console.log('Request already in progress for key:', key)
return
}
stock.isLoading = true
console.log('Making actual request for key:', key)
cb(...args)
.then((res) => {
console.log('Request succeeded for key:', key)
stock.resolve.forEach((resolve: any) => resolve(res))
})
.catch((err) => {
console.log('Request failed for key:', key, 'Error:', err)
stock.reject.forEach((reject: any) => reject(err))
})
.finally(() => {
console.log('Clearing cache for key:', key)
map[key] = null
})
})
}
}
export const getData = asyncFun(loadData) as typeof loadData
效果:只发送了一次请求(相同请求)
总结
以上就是今天要讲的内容,本文仅仅简单介绍了异步请求发送时重复问题,可以减少服务器压力提高性能。