Vue3+vite中Axios的配置和使用方法

在Vue3中使用Axios可以通过以下步骤来完成配置和使用:

  1. 安装Axios:
npm install axios
  1. 在项目中创建一个api.js文件,并导入Axios和Vue:
import axios from 'axios'
import { reactive } from 'vue'
  1. 创建一个响应式对象并将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'
  }
})
  1. 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
  }
}
  1. 在组件中导入api.js并调用方法:
import { fetchData } from '@/api'

export default {
  name: 'MyComponent',
  async created() {
    await fetchData()
  }
}
  1. 在模板中使用响应式数据:
<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的配置和使用方法。

猜你喜欢

转载自blog.csdn.net/qq_44848480/article/details/131434369