Axios 發起 HTTP 請求 - daniel-qa/Vue GitHub Wiki

Axios 發起 HTTP 請求

  • EX
    const fetchGeosData = async () => {

        const data = {
            countryId: "CN",
            provinceId: "51",
            cityId: "511600"
        };

        try {
            const response = await axios.post('https://localhost:5001/notice/get-geos', data);

            console.log("status :" + response.data.state);

            // 解构数据
            const { state, result } = response.data;

            if (state === 200) {

                console.error('Success')
            } else {
                console.error('请求失败,状态码或响应状态异常:', response.status, response.data.state)
            }

        } catch (error) {
            console.error('请求失败:', error);
        }       
    };

在 Vue 3 中,使用 ref 可以直接绑定动态数据,而不需要预定义固定的数据结构。如果接口返回的数据格式是稳定的,你可以直接操作接口返回的数据,例如访问 school.tchCnt,不需要额外定义结构。

<li v-for="school in response" :key="school.id">
  {{ school.name }} (教师数: {{ school.tchCnt || 0 }}, 学生数: {{ school.scCnt || 0 }})
</li>

  • 取得資料 API

 import axios from 'axios';

 // 获取组件实例的 proxy
 const { proxy } = getCurrentInstance(); 

  try {
  	const response = await axios.post('https://localhost:5001/notice/get-areas', data);
  
  
  	console.log("status :" + response.data.state);
  
  	console.log("id :" + response.data.result[0].id);
  
  	console.log("school name:" + response.data.result[0].schools[0].name);
  
  	console.log("school id:" + response.data.result[0].schools[0].id);
  
  	// 解构数据
  	const { state, result } = response.data;
  
  	
  	if (state === 200) {
  		// 将返回的数据格式化为级联选择器需要的格式
  		cascaderOptions.value = result.map(area => ({
  			value: area.id, // 学区ID
  			label: area.name, // 学区名称
  			children: area.schools.map(school => ({
  				value: school.id, // 学校ID
  				label: school.name // 学校名称
  			}))
  		}))
  	} else {
  		console.error('请求失败,状态码或响应状态异常:', response.status, response.data.state)
  	}
  
  } catch (error) {
  	console.error('请求失败:', error);
  }

  • EX
import axios from 'axios';

const fetchData = async () => {
    const data = {
        // 可以随意定义需要传递的内容
        areaId: '12345',
        showSchool: true,
    };

    const response = {
        data: {
            state: 200,
            result: [
                {
                    id: '02944f32-f534-3397-ea56-e6f1fc6c3714',
                    name: '醍摩豆智慧学区',
                    scCnt: 1,
                    tchCnt: 7,
                    schools: [],
                },
            ],
        },
    };

    try {
        const response = await axios.post('https://localhost:5001/notice/get-areas', data);
        
        // 解构数据
        const { state, result } = response.data;

        if (state === 200) {
            console.log('请求成功,解析结果:');
            result.forEach((area, index) => {
                console.log(`=== 学区 ${index + 1} ===`);
                console.log(`学区ID: ${area.id}`);
                console.log(`学区名称: ${area.name}`);
                console.log(`学校数量: ${area.scCnt}`);
                console.log(`老师数量: ${area.tchCnt}`);
                console.log(`学校列表: ${JSON.stringify(area.schools)}`); // JSON 序列化空数组
            });
        } else {
            console.error('请求失败,状态码或响应状态异常:', response.status, response.data.state);
        }

    } catch (error) {
        console.error('请求失败:', error);
    }
};
// 檢查內容
console.log("status :" + response.data.state);

console.log("id :" + response.data.result[0].id);

console.log("school name:" + response.data.result[0].schools[0].name);

console.log("school id:" + response.data.result[0].schools[0].id);

  • EX2 :
<template>
  <div>
    <h1>学区学校列表</h1>
    <ul v-if="areaList.length">
      <li v-for="(area, index) in areaList" :key="index">{{ area.name }}</li>
    </ul>
    <p v-else>正在加载...</p>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus' // 引入 Element Plus 的 ElMessage

const areaList = ref([])

const getArealist = async () => {
  try {
    const response = await axios.get('https://api.example.com/capacity')

    if (response.status === 200) {
      areaList.value = response.data.areas
    } else {
      ElMessage.error(`请求失败,状态码:${response.status}`)
    }
  } catch (error) {
    ElMessage.error('API 请求失败')
    console.error('请求错误:', error)
  }
}

onMounted(() => {
  getArealist()
})
</script>

<style scoped>
/* 你可以在这里添加样式 */
</style>

⚠️ **GitHub.com Fallback** ⚠️