关于Vue.如何封装Axios以减少请求代码冗余



现在我正在使用Vue编写一个项目。我使用了很多Axios请求,如何封装请求代码以减少冗余。

getProvinces() {
this.axios
.get(this.gv.serverUrl + "/location/province/list")
.then((res) => {
this.location.province.provinces = res.data.data;
});
},
getCities() {
this.axios
.get(this.gv.serverUrl + "/location/city/list", {
params: {
pid: this.location.province.province,
},
})
.then((res) => {
this.location.city.cities = res.data.data;
});
},
getCountries() {
this.axios
.get(this.gv.serverUrl + "/location/country/list", {
params: {
cid: this.location.city.city,
},
})
.then((res) => {
this.location.country.countries = res.data.data;
});
},

使用Axios.all执行并发请求。这将帮助您封装所有请求的状态。不完全是这样,但如下所示:

let endpoints = [
'https://this.gv.serverUrl + "/location/province/list"',
'https://this.gv.serverUrl + "/location/city/list"',
'https://api.github.com/users/ejirocodes/followers',
'https://api.github.com/users/ejirocodes/following'
];
axios.all(endpoints.map((endpoint) => axios.get(endpoint))).then(
(data) => console.log(data),
)

以下是获取更多帮助和良好解释的链接:https://blog.logrocket.com/using-axios-all-make-concurrent-requests/

您可以创建一个方法来进行axios调用,传递路径和params(作为可选参数(。因此,一种适用于您提供的代码的方法可能是:

fetch(resource, params) {
return this.axios.get(this.gv.serverUrl + `/location/${resource}/list`, { params })

这个fetch方法将返回一个promise,您的方法将如下所示:

getProvinces() {
this.fetch("/location/province/list")
.then((res) => {
this.location.province.provinces = res.data.data;
});
},
getCities() {
this.fetch("/location/city/list", { pid: this.location.province.province })
.then((res) => {
this.location.city.cities = res.data.data;
});
},
getCountries() {
this.fetch("/location/country/list", { cid: this.location.city.city})
.then((res) => {
this.location.country.countries = res.data.data;
});
},

如果Vue实例的数据属性存在某种一致性,则可以进行进一步的重构。我看不到你的数据属性的形状,但从我所看到的情况来看,它看起来像这样:

data() {
return {
location: {
province: {
provinces: [...],
},
city: {
cities: [...],
},
country: {
countries: [...],
},
}
}
}

如果你能把它改成这样的东西:

data() {
return {
location: {
province: {
list: [...],
},
city: {
list: [...],
},
country: {
list: [...],
},
}
}

那么方法的重构可能是这样的:

fetch(resource, params) {
return this.axios
.get(this.gv.serverUrl + `/location/${resource}/list`, { params })
.then((res) => {
this.location[resource].list = res.data.data;
})
getProvinces() {
this.fetch("/location/province/list")
},
getCities() {
this.fetch("/location/city/list", { pid: this.location.province.province })
},
getCountries() {
this.fetch("/location/country/list", { cid: this.location.city.city})
},

最新更新