真实应用的 Axios 技巧
以下是我收集的一些有用的模式和技巧,用于在您的 Web 应用程序中使用axios管理 API 请求。
模块
网上有很多示例,其中 API 端点 URL 被硬编码到组件方法或生命周期钩子中。
这样做没什么问题,尤其是在你只有几个 API 端点的情况下。然而,在大型应用程序中,创建一个专门用于处理请求的模块可能会更好。
这是一个硬编码 axios 请求的典型示例。
async function fetchData () {
try {
this.isLoading = true
const response = await axios.get('/api/items') // <-------
this.items = response.data
} catch (error) {
// handle error
} finally {
this.isLoading = false
}
}
让我们创建我们的 API 模块。
// api.js
import axios from 'axios'
export default {
getItems: params => axios.get('/api/items', { params }),
createItem: item => axios.post('/api/items', item),
// etc.
}
现在,我们可以在一个文件中轻松查看和更新所有端点,而应用程序的其余部分则不再关心如何或在何处获取数据。
import api from './api'
// Inside your async method, component lifecycle hook, etc.
const response = await api.getItems()
// We can use the same method with our optional params argument
const response = await api.getItems({ id: 9 })
如果您的 API 有许多路由,那么将您的模块组织到命名空间中可能是有意义的。
// api.js
const comments = {
get: params => axios.get('/api/v2/comments', { params }),
delete: params => axios.delete('/api/v2/comments', { params }),
// etc.
}
const posts = {
get: params => axios.get('/api/v2/posts', { params }),
// etc.
}
export default {
comments,
posts
}
const responses = await Promise.all(
api.posts.get({ id }),
api.comments.get({ postId: id })
)
如果您是 Vue 用户,并且发现自己将 api 模块导入到许多组件中,那么请考虑将其添加到 Vue 原型中。
// main.js
import api from '@/api'
import Vue from 'vue'
// ...
Vue.prototype.$api = api
const app = new Vue({
// ...
现在,您的所有组件都将继承该属性this.$api
。
// MyComponent.vue
methods: {
async getCat (id) {
try {
this.isLoading = true
const { data } = await this.$api.getCat(id)
} catch (error) {
// handle error
} finally {
this.isLoading = false
}
}
}
基地路线
我们不想不断重复我们的基本路由和版本(/api/v2
)。为了避免这种情况,我们的首选方案是简单地向模板字符串中添加一些变量。
const version = '2'
const API = `/api/${version}`
export default {
getComments: params => axios.get(`${API}/comments`, params)
}
更好的选择是创建一个专门针对我们的基本路线的 axios实例。
const API = axios.create({
baseURL: '/api/v2'
})
export default {
getComments: params => API.get('/comments', params)
}
如果你的 API 版本控制是通过标头而不是路由完成的,那么创建 axios 实例会特别方便。只需headers
向 config 对象添加一个属性即可axios.create
。
const API = axios.create({
baseURL: '/api',
headers: { 'Accept-Version': '~2' }
})
您的申请
根据您对应用程序的需求,混合并搭配上述任何或所有提示。
也许您的 Vue 应用程序不需要 API 模块,但您仍然需要一个针对您的基本路由的全局 axios 实例。
// main.js
import axios from 'axios'
import Vue from vue
const baseURL = '/api/v2'
Vue.prototype.$axios = axios.create({ baseURL })
// YourComponent.vue
this.$axios.post('/cats', data) // equivalent to axios.post('/api/v2/cats', data)
请务必花些时间仔细阅读axios 文档,因为它有很多很棒的功能。感谢阅读!
鏂囩珷鏉ユ簮锛�https://dev.to/kevinleedrum/axios-tips-for-real-world-apps-3bo4