数据请求
Axios、TanStack Query 与 Apollo。
数据请求
这一课你将能做到
- 用原生
fetch发送 HTTP 请求 - 用
axios发送请求并配置拦截器 - 在组件中管理 loading 和 error 状态
- 封装通用的
useFetch组合式函数
为什么要学
前端不是孤岛,数据都在后端服务器上。不会发请求,你的页面只能展示写死的数据。掌握数据请求,才能做真正的「动态应用」。
人话:数据请求就像「点外卖」。你(前端)告诉外卖平台(后端 API)要什么,平台做好后送给你。过程中你要等(loading),可能送错(error),送到后开吃(渲染数据)。
先建立图像
<script setup>
import { ref, onMounted } from 'vue'
const users = ref([])
const loading = ref(true)
const error = ref(null)
onMounted(async () => {
try {
const res = await fetch('https://jsonplaceholder.typicode.com/users')
users.value = await res.json()
} catch (e) {
error.value = e.message
} finally {
loading.value = false
}
})
</script>
<template>
<p v-if="loading">加载中...</p>
<p v-else-if="error">出错了:{{ error }}</p>
<ul v-else>
<li v-for="u in users" :key="u.id">{{ u.name }}</li>
</ul>
</template>
跟着做
步骤 1:原生 fetch 基础
// GET 请求
const res = await fetch('https://api.example.com/users')
const data = await res.json()
// POST 请求
const res = await fetch('https://api.example.com/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: '张三', age: 25 })
})
const data = await res.json()
步骤 2:axios 安装与使用
npm install axios
import axios from 'axios'
// GET
const res = await axios.get('https://api.example.com/users')
console.log(res.data) // axios 自动解析 JSON
// POST
const res = await axios.post('https://api.example.com/users', {
name: '张三'
})
步骤 3:axios 拦截器
// api/request.js
import axios from 'axios'
const request = axios.create({
baseURL: 'https://api.example.com',
timeout: 10000
})
// 请求拦截器:自动加 token
request.interceptors.request.use(config => {
const token = localStorage.getItem('token')
if (token) config.headers.Authorization = `Bearer ${token}`
return config
})
// 响应拦截器:统一处理错误
request.interceptors.response.use(
res => res.data,
err => {
if (err.response?.status === 401) {
// 跳转登录
router.push('/login')
}
return Promise.reject(err)
}
)
export default request