在Vue3中使用Axios可以通过以下步骤来完成配置和使用:
- 安装Axios:
npm install axios
- 在项目中创建一个
api.js
文件,并导入Axios和Vue:
import axios from 'axios'
import { reactive } from 'vue'
- 创建一个响应式对象并将Axios实例化:
const state = reactive({
data: null,
loading: false,
error: null
})
const http = axios.create({
baseURL: 'https://api.example.com/v1',
timeout: 10000,
headers: {
'Content-Type': 'application/json'
}
})
- 在
api.js
文件中创建方法来发送HTTP请求:
const fetchData = async () => {
state.loading = true
try {
const response = await http.get('/data')
state.data = response.data
} catch (error) {
state.error = error
} finally {
state.loading = false
}
}
- 在组件中导入
api.js
并调用方法:
import { fetchData } from '@/api'
export default {
name: 'MyComponent',
async created() {
await fetchData()
}
}
- 在模板中使用响应式数据:
<template>
<div v-if="state.loading">Loading...</div>
<div v-else-if="state.error">{
{ state.error.message }}</div>
<div v-else>{
{ state.data }}</div>
</template>
<script>
import { state } from '@/api'
export default {
name: 'MyComponent',
setup() {
return { state }
}
}
</script>
以上就是在Vue3中使用Axios的配置和使用方法。