Vue3請(qǐng)求后端接口實(shí)現(xiàn)方式
在Vue3應(yīng)用中,與后端API交互是實(shí)現(xiàn)動(dòng)態(tài)數(shù)據(jù)展示的核心環(huán)節(jié)。
本文將通過(guò)??原生Fetch API??和??Axios庫(kù)??兩種常用方式,詳細(xì)講解如何在Vue3組件中發(fā)起請(qǐng)求、處理響應(yīng)、管理狀態(tài)及解決常見(jiàn)問(wèn)題,幫助你構(gòu)建高效、可維護(hù)的前后端交互邏輯。
一、準(zhǔn)備工作
在開(kāi)始之前,請(qǐng)確保你的開(kāi)發(fā)環(huán)境已安裝以下工具:
- ??Node.js??(≥16.0):用于運(yùn)行Vue項(xiàng)目;
- ??Vue CLI??:用于創(chuàng)建和管理Vue3項(xiàng)目(若未安裝,可通過(guò)
npm install -g @vue/cli全局安裝)。
創(chuàng)建一個(gè)新的Vue3項(xiàng)目:
vue create vue3-api-tutorial cd vue3-api-tutorial
選擇“Vue 3”配置即可完成項(xiàng)目初始化。
二、使用原生Fetch API請(qǐng)求后端
Fetch API是現(xiàn)代瀏覽器內(nèi)置的HTTP請(qǐng)求工具,無(wú)需額外安裝依賴,適合簡(jiǎn)單的GET/POST請(qǐng)求。
1. 基礎(chǔ)GET請(qǐng)求示例
在src/components目錄下創(chuàng)建FetchExample.vue組件,代碼如下:
<template>
<div>
<h1>用戶列表(Fetch API)</h1>
<!-- 加載狀態(tài)提示 -->
<div v-if="loading">加載中...</div>
<!-- 錯(cuò)誤信息提示 -->
<div v-if="errorMsg" style="color: red;">{{ errorMsg }}</div>
<!-- 數(shù)據(jù)展示 -->
<ul v-if="users.length && !loading">
<li v-for="user in users" :key="user.id">{{ user.name }} ({{ user.email }})</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
users: [], // 存儲(chǔ)用戶數(shù)據(jù)
loading: false, // 加載狀態(tài)
errorMsg: '' // 錯(cuò)誤信息
}
},
mounted() {
this.fetchUsers(); // 組件掛載后自動(dòng)發(fā)起請(qǐng)求
},
methods: {
async fetchUsers() {
this.loading = true; // 開(kāi)啟加載狀態(tài)
this.errorMsg = ''; // 清空錯(cuò)誤信息
try {
// 發(fā)起GET請(qǐng)求(使用JSONPlaceholder測(cè)試API)
const response = await fetch('https://jsonplaceholder.typicode.com/users');
if (!response.ok) { // 檢查響應(yīng)狀態(tài)(非200-299視為錯(cuò)誤)
throw new Error(`網(wǎng)絡(luò)響應(yīng)異常:${response.status}`);
}
const data = await response.json(); // 解析JSON數(shù)據(jù)
this.users = data; // 更新組件數(shù)據(jù)
} catch (error) {
this.errorMsg = `獲取數(shù)據(jù)失?。?{error.message}`; // 捕獲并顯示錯(cuò)誤
console.error('Fetch請(qǐng)求錯(cuò)誤:', error);
} finally {
this.loading = false; // 關(guān)閉加載狀態(tài)
}
}
}
}
</script>2. POST請(qǐng)求示例(提交表單數(shù)據(jù))
若需要向后臺(tái)提交數(shù)據(jù)(如用戶登錄),可使用Fetch API的POST方法:
methods: {
async loginUser() {
const userData = { username: 'admin', password: '123456' };
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json' // 聲明請(qǐng)求體格式為JSON
},
body: JSON.stringify(userData) // 將JavaScript對(duì)象轉(zhuǎn)為JSON字符串
});
const result = await response.json();
console.log('登錄成功:', result);
} catch (error) {
console.error('登錄失?。?, error);
}
}
}3. 注意事項(xiàng)
- ??跨域問(wèn)題??:若前端(
http://localhost:8080)與后端(http://localhost:5000)不在同一端口,需在后端配置CORS(如Flask中使用flask-cors庫(kù))或在Vue項(xiàng)目中配置代理(見(jiàn)下文“常見(jiàn)問(wèn)題解決”); - ??錯(cuò)誤處理??:務(wù)必捕獲
fetch的catch錯(cuò)誤,并提示用戶友好的錯(cuò)誤信息; - ??加載狀態(tài)??:通過(guò)
loading屬性控制加載提示,提升用戶體驗(yàn)。
三、使用Axios庫(kù)請(qǐng)求后端
Axios是基于Promise的HTTP客戶端,支持請(qǐng)求/響應(yīng)攔截、自動(dòng)JSON轉(zhuǎn)換、取消請(qǐng)求等功能,更適合復(fù)雜項(xiàng)目。
1. 安裝Axios
npm install axios
2. 封裝Axios實(shí)例(推薦)
為統(tǒng)一管理請(qǐng)求配置(如baseURL、超時(shí)時(shí)間、攔截器),建議創(chuàng)建一個(gè)src/utils/request.js文件:
import axios from 'axios';
// 創(chuàng)建Axios實(shí)例
const request = axios.create({
baseURL: '/api', // 基礎(chǔ)路徑(可根據(jù)環(huán)境變量動(dòng)態(tài)設(shè)置)
timeout: 5000 // 請(qǐng)求超時(shí)時(shí)間(毫秒)
});
// 請(qǐng)求攔截器:在發(fā)送請(qǐng)求前處理(如添加token)
request.interceptors.request.use(
config => {
const token = localStorage.getItem('token');
if (token) {
config.headers['Authorization'] = `Bearer ${token}`; // 添加認(rèn)證頭
}
return config;
},
error => Promise.reject(error) // 攔截請(qǐng)求錯(cuò)誤
);
// 響應(yīng)攔截器:統(tǒng)一處理響應(yīng)(如判斷狀態(tài)碼)
request.interceptors.response.use(
response => {
// 假設(shè)后端返回格式為 { code: 0, data: {}, message: '' }
if (response.data.code !== 0) {
return Promise.reject(response.data.message); // 非0狀態(tài)碼視為錯(cuò)誤
}
return response.data.data; // 返回實(shí)際數(shù)據(jù)
},
error => {
console.error('請(qǐng)求錯(cuò)誤:', error);
return Promise.reject(error.message || '網(wǎng)絡(luò)異常'); // 統(tǒng)一錯(cuò)誤提示
}
);
export default request;3. 在組件中使用Axios
創(chuàng)建src/components/AxiosExample.vue組件:
<template>
<div>
<h1>用戶列表(Axios)</h1>
<div v-if="loading">加載中...</div>
<div v-if="errorMsg" style="color: red;">{{ errorMsg }}</div>
<ul v-if="users.length && !loading">
<li v-for="user in users" :key="user.id">{{ user.name }} ({{ user.email }})</li>
</ul>
</div>
</template>
<script>
import request from '@/utils/request'; // 引入封裝的Axios實(shí)例
export default {
data() {
return {
users: [],
loading: false,
errorMsg: ''
}
},
mounted() {
this.fetchUsers();
},
methods: {
async fetchUsers() {
this.loading = true;
this.errorMsg = '';
try {
// 發(fā)起GET請(qǐng)求(自動(dòng)拼接baseURL:/api/users)
const response = await request.get('/users');
this.users = response; // 直接使用攔截器處理后的數(shù)據(jù)
} catch (error) {
this.errorMsg = `獲取數(shù)據(jù)失?。?{error}`;
} finally {
this.loading = false;
}
}
}
}
</script>4. 封裝通用API函數(shù)(可選)
為提高代碼復(fù)用性,可將不同接口封裝為獨(dú)立函數(shù),存放在src/api/user.js中:
import request from '@/utils/request';
// 登錄接口
export function login(data) {
return request.post('/user/login', data);
}
// 獲取用戶信息接口
export function getUserInfo() {
return request.get('/user/info');
}
// 獲取用戶列表接口
export function getUserList() {
return request.get('/users');
}組件中調(diào)用時(shí),只需引入對(duì)應(yīng)函數(shù)即可:
import { getUserList } from '@/api/user';
async fetchUsers() {
this.loading = true;
try {
this.users = await getUserList();
} catch (error) {
this.errorMsg = error;
} finally {
this.loading = false;
}
}5. Axios的優(yōu)勢(shì)
- ??攔截器??:統(tǒng)一處理token、錯(cuò)誤提示、請(qǐng)求loading;
- ??自動(dòng)轉(zhuǎn)換??:自動(dòng)將JSON響應(yīng)轉(zhuǎn)為JavaScript對(duì)象;
- ??取消請(qǐng)求??:支持通過(guò)
CancelToken取消未完成的請(qǐng)求; - ??并發(fā)請(qǐng)求??:通過(guò)
axios.all同時(shí)發(fā)起多個(gè)請(qǐng)求。
四、常見(jiàn)問(wèn)題解決
1. 跨域問(wèn)題
若前端與后端不在同一域名/端口,需配置代理(以Vite為例):
- 在
vite.config.js中添加代理配置:
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [vue()],
server: {
proxy: {
'/api': { // 匹配以/api開(kāi)頭的請(qǐng)求
target: 'http://localhost:5000', // 后端服務(wù)器地址
changeOrigin: true, // 改變請(qǐng)求頭中的origin為目標(biāo)URL
rewrite: path => path.replace(/^\/api/, '') // 去除請(qǐng)求路徑中的/api前綴
}
}
}
});- 修改Axios實(shí)例的
baseURL為/api,即可通過(guò)/api/users訪問(wèn)后端的http://localhost:5000/users。
2. 響應(yīng)數(shù)據(jù)格式處理
若后端返回的數(shù)據(jù)格式與攔截器預(yù)設(shè)不一致(如{ status: 200, data: {}, msg: '' }),需調(diào)整攔截器邏輯:
request.interceptors.response.use(
response => {
if (response.data.status !== 200) {
return Promise.reject(response.data.msg);
}
return response.data.data; // 返回實(shí)際數(shù)據(jù)
}
);3. Token失效處理
在響應(yīng)攔截器中判斷token失效(如狀態(tài)碼401),并跳轉(zhuǎn)至登錄頁(yè):
request.interceptors.response.use(
response => response.data.data,
error => {
if (error.response && error.response.status === 401) {
window.location.href = '/login'; // 跳轉(zhuǎn)登錄頁(yè)
}
return Promise.reject(error.message);
}
);五、總結(jié)
本文通過(guò)Fetch API和Axios兩種方式,詳細(xì)講解了Vue3中請(qǐng)求后端接口的完整流程,包括基礎(chǔ)請(qǐng)求、狀態(tài)管理、錯(cuò)誤處理及常見(jiàn)問(wèn)題解決。??
推薦優(yōu)先使用Axios??,其豐富的功能和良好的可維護(hù)性更適合復(fù)雜項(xiàng)目。在實(shí)際開(kāi)發(fā)中,建議通過(guò)封裝Axios實(shí)例和API函數(shù),統(tǒng)一管理請(qǐng)求配置,提升團(tuán)隊(duì)協(xié)作效率。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- Vue3 + vue-query 的重復(fù)請(qǐng)求問(wèn)題解決
- vue3前端axios請(qǐng)求報(bào)錯(cuò)network錯(cuò)誤的解決辦法
- 前端vue3使用SSE、EventSource攜帶請(qǐng)求頭實(shí)例代碼
- 一文詳解如何在Vue3中封裝API請(qǐng)求
- 解決vite+vue3項(xiàng)目打包后圖片不顯示或者請(qǐng)求路徑多了一個(gè)undefined問(wèn)題
- vue3配置代理實(shí)現(xiàn)axios請(qǐng)求本地接口返回PG庫(kù)數(shù)據(jù)
- vue3和beego跨域請(qǐng)求配置方式
相關(guān)文章
Vue中@click.native的使用方法及場(chǎng)景
在組件中時(shí)??吹紷click.native,在項(xiàng)目中遇到后,簡(jiǎn)單介紹下,這篇文章主要給大家介紹了關(guān)于Vue中@click.native的使用方法及場(chǎng)景的相關(guān)資料,需要的朋友可以參考下2023-11-11
幫助我們高效操作的Virtual?DOM簡(jiǎn)單實(shí)現(xiàn)
這篇文章主要為大家介紹了幫助我們高效操作Virtual?DOM簡(jiǎn)單實(shí)現(xiàn)及原理解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
解決ant-design-vue中menu菜單無(wú)法默認(rèn)展開(kāi)的問(wèn)題
這篇文章主要介紹了解決ant-design-vue中menu菜單無(wú)法默認(rèn)展開(kāi)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-10-10
Vue+tracking.js 實(shí)現(xiàn)前端人臉檢測(cè)功能
這篇文章主要介紹了Vue+tracking.js 實(shí)現(xiàn)前端人臉檢測(cè)功能,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-04-04
基于vue+echarts 數(shù)據(jù)可視化大屏展示的方法示例
這篇文章主要介紹了基于vue+echarts 數(shù)據(jù)可視化大屏展示的方法示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2020-03-03

