axios 非同步和同步 - daniel-qa/Vue GitHub Wiki
在 Vue 3 中使用 Axios 進行 POST 請求時,預設是非同步的。如果要同步操作,通常需要等待 async/await 來確保順序執行。以下是最簡單的範例。
這是最常見的寫法,使用 .then() 和 .catch() 處理請求。
<template>
<el-button @click="postData">發送非同步請求</el-button>
</template>
<script setup>
import axios from 'axios';
const postData = () => {
axios.post('/api/example', { name: 'John Doe' })
.then(response => {
console.log('非同步回應:', response.data);
})
.catch(error => {
console.error('發生錯誤:', error);
});
};
</script>
這種方式讓程式碼看起來像同步操作,但仍然是非同步執行的。
<template>
<el-button @click="postData">發送同步風格請求</el-button>
</template>
<script setup>
import axios from 'axios';
const postData = async () => {
try {
const response = await axios.post('/api/example', { name: 'Jane Doe' });
console.log('同步風格回應:', response.data);
} catch (error) {
console.error('發生錯誤:', error);
}
};
</script>
JavaScript 是單執行緒的,無法真正阻塞式同步,但可以使用 async/await 模擬順序執行。
<template>
<el-button @click="handleTasks">按順序執行多個請求</el-button>
</template>
<script setup>
import axios from 'axios';
const handleTasks = async () => {
console.log('開始請求 1');
const res1 = await axios.post('/api/task1', { task: '第一個請求' });
console.log('請求 1 完成:', res1.data);
console.log('開始請求 2');
const res2 = await axios.post('/api/task2', { task: '第二個請求' });
console.log('請求 2 完成:', res2.data);
};
</script>
-
箭頭函式 (const search = async () => {}):常用於組件內的事件處理、短小邏輯。
-
傳統函式 (async function search() {}):適用於大型模組函式、需要更明確函式定義的情境。
<template>
<el-button @click="search">發送 API 請求</el-button>
</template>
<script setup>
import axios from 'axios';
const search = async () => {
try {
const response = await axios.get('https://api.example.com/data');
console.log('回應:', response.data);
} catch (error) {
console.error('錯誤:', error);
}
};
</script>
適用於大型模組函式或更清晰的函式定義
在處理較為複雜的邏輯或需要在多個地方重複使用的函式時,傳統函式更為直觀。
<template>
<el-button @click="search">發送 API 請求</el-button>
</template>
<script setup>
import axios from 'axios';
async function search() {
try {
const response = await axios.get('https://api.example.com/data');
console.log('回應:', response.data);
} catch (error) {
console.error('錯誤:', error);
}
}
</script>
箭頭函式不會改變 this 的指向。它會繼承它被創建時的外部上下文中的 this,這就是所謂的「綁定」this。
換句話說,箭頭函式的 this 是在函式被創建時決定的,而不是在呼叫時決定的。