在Vue3中封装axios可以按照以下步骤进行:

  1. 安装axios和@vue/composition-api:
npm install axios @vue/composition-api
  1. 创建一个axios实例,并设置一些默认配置:
import axios from 'axios';

const instance = axios.create({
  baseURL: 'http://api.example.com',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
});

export default instance;
  1. 创建一个封装axios的函数:
import { ref } from '@vue/composition-api';
import axiosInstance from './axiosInstance';

export default function useAxios() {
  const loading = ref(false);
  const error = ref(null);
  const data = ref(null);

  const fetchData = async (url) => {
    loading.value = true;
    try {
      const response = await axiosInstance.get(url);
      data.value = response.data;
    } catch (err) {
      error.value = err.message;
    } finally {
      loading.value = false;
    }
  };

  return { loading, error, data, fetchData };
}
  1. 在组件中使用封装的axios函数:
<template>
  <div>
    <button @click="fetchData">Fetch Data</button>
    <div v-if="loading">Loading...</div>
    <div v-if="error">Error: {{ error }}</div>
    <div v-if="data">{{ data }}</div>
  </div>
</template>

<script>
import useAxios from './useAxios';

export default {
  setup() {
    const { loading, error, data, fetchData } = useAxios();

    return {
      loading,
      error,
      data,
      fetchData
    };
  }
}
</script>

这样就完成了在Vue3中封装axios的过程。在组件中使用fetchData函数来获取数据,并通过loadingerrordata来展示加载状态、错误信息和数据

vue3封装axios

原文地址: https://www.cveoy.top/t/topic/hyYN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录