Configuration and usage of Axios in Vue3+vite

Using Axios in Vue3 can be configured and used through the following steps:

  1. Install Axios:
npm install axios
  1. Create a file in your project api.jsand import Axios and Vue:
import axios from 'axios'
import { reactive } from 'vue'
  1. Create a reactive object and instantiate 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. Create methods in api.jsthe file to send HTTP requests:
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.jsImport and call the method in the component :
import { fetchData } from '@/api'

export default {
  name: 'MyComponent',
  async created() {
    await fetchData()
  }
}
  1. Use reactive data in templates:
<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>

The above is how to configure and use Axios in Vue3.

Guess you like

Origin blog.csdn.net/qq_44848480/article/details/131434369