在Vue基础第6篇中,我们学习了使用Pinia集中管理多个组件共享的状态。
现在,应用内部的数据流已经能够清楚地组织起来。
第7篇介绍Vue应用如何与外部服务器通信。
现代Web应用通常不会自己保存所有数据,而是在需要时向服务器请求,再动态更新界面。
这种与服务器通信的过程称为
API对接
。
它以异步(Asynchronous)方式执行,今天重点介绍让异步通信更加方便的
axios库。
首先在项目中安装Axios。
在终端执行以下命令。
安装后,可以像实际项目一样,创建一个预先指定API基础地址等公共配置的Axios实例,避免重复设置。
在
src下创建
api文件夹,再创建
index.js。
src/api/index.js import axios from 'axios' ;
// Axios 인스턴스를 생성합니다.
const api = axios. create ({
// API 요청의 기본 주소를 설정합니다.
// 모든 요청 앞에 이 주소가 붙게 됩니다.
baseURL: 'https://jsonplaceholder.typicode.com'
});
export default api;
有了实例,之后就能用简洁的api.get('/posts'),代替axios.get('https://jsonplaceholder.typicode.com/posts')。
那么,应该在组件的哪个阶段调用API?
这就需要了解
生命周期钩子(Lifecycle Hooks)
。
它们是Vue在组件创建、挂载、更新和销毁等阶段自动执行的函数。
通过API获取初始显示数据,通常在组件挂载到界面后执行。
此时使用的钩子是
onMounted。
PostList.vue < script setup >
import { ref, onMounted } from 'vue' ;
import api from '@/api' ; // 우리가 만든 Axios 인스턴스를 가져옵니다.
const posts = ref ([]);
// onMounted 훅에 비동기 함수를 전달합니다.
onMounted ( async () => {
try {
// 컴포넌트가 마운트되면 API를 호출하여 게시물 목록을 가져옵니다.
const response = await api. get ( '/posts?_limit=10' ); // 10개만 가져오기
posts.value = response.data; // 응답 데이터를 posts 상태에 저장합니다.
} catch (error) {
console. error ( '데이터를 가져오는 중 에러 발생:' , error);
}
});
</ script >
< template >
< div >
< h1 >게시물 목록</ h1 >
< ul >
< li v-for = " post in posts " : key = " post.id " >
{{ post.title }}
</ li >
</ ul >
</ div >
</ template >
上面的代码会在PostList组件准备好后,立即调用/posts API,并将响应中的文章列表显示在界面上。
实际服务中,网络可能缓慢,服务器也可能出问题。
如果没有处理这些情况,用户可能只能看到空白界面,或不知道应用为什么没有响应。
因此,调用API时管理*加载(loading)
和
错误(error)*状态非常重要。
使用
try...catch...finally可以清楚地实现这些逻辑。
PostList.vue < script setup >
import { ref, onMounted } from 'vue' ;
import api from '@/api' ;
const posts = ref ([]);
const isLoading = ref ( false ); // 로딩 상태를 관리할 ref
const error = ref ( null ); // 에러 상태를 관리할 ref
onMounted ( async () => {
isLoading.value = true ; // API 호출 시작 전에 로딩 상태를 true로 설정
error.value = null ;
try {
// try 블록 안에서 API를 호출합니다.
const response = await api. get ( '/posts?_limit=10' );
posts.value = response.data;
} catch (err) {
// catch 블록에서 에러를 처리합니다.
console. error ( '데이터를 가져오는 중 에러 발생:' , err);
error.value = '데이터를 불러올 수 없습니다. 잠시 후 다시 시도해주세요.' ;
} finally {
// finally 블록은 성공/실패 여부와 관계없이 항상 실행됩니다.
isLoading.value = false ; // API 호출이 끝나면 로딩 상태를 false로 설정
}
});
</ script >
< template >
< div >
< h1 >게시물 목록</ h1 >
< div v-if = " isLoading " >
로딩 중입니다...
</ div >
< div v-else-if = " error " >
< p style = " color : red ; " >{{ error }}</ p >
</ div >
< ul v-else >
< li v-for = " post in posts " : key = " post.id " >
{{ post.title }}
</ li >
</ ul >
</ div >
</ template >
这样,用户就能知道数据是否正在加载,或者是否发生了问题,体验也会更好。
本篇学习了Vue应用与外部服务器通信所需的API对接方法。
熟练处理异步数据,是构建现代动态Web应用的核心能力之一。
下一篇Vue基础第8篇,将介绍组件样式管理,以及根据特定条件显示或隐藏部分界面的条件渲染。