axios.post()
可簡單呼叫 POST REST API。
Version
Vue 3.4
Axios 1.6.7
POST
App.vue
<template>
<input type="text" v-model="newTodo" />
<button @click="onAdd">Add</button>
</template>
<script setup>
import axios from 'axios'
import { ref } from 'vue'
let newTodo = ref('')
let onAdd = async () => {
if (newTodo.value === '') return
let url = 'http://localhost:3000/todos'
let body = {
isCompleted: false,
todo: newTodo.value
}
try {
await axios.post(url, body)
} catch (e) {
console.error(e)
}
newTodo.value = ''
}
</script>
Line 2
<input type="text" v-model="newTodo" />
v-model
:將輸入的新 todo 綁定到newTodo
state
Line 3
<button @click="onAdd">Add</button>
- 新增一筆 todo,並將
click
event 指定到onAdd()
Line 7
import axios from 'axios'
- 引用 Axios
Line 10
let newTodo = ref('')
newTodo
state:儲存新輸入的 todo
Line 12
let onAdd = async () => {
if (newTodo.value === '') return
let url = 'http://localhost:3000/todos'
let body = {
isCompleted: false,
todo: newTodo.value
}
try {
await axios.post(url, body)
} catch (e) {
console.error(e)
}
newTodo.value = ''
}
- JSON Server 會自動處理
id
欄位,body
可以不用處理 - 將
url
與body
傳入axios.post()
呼叫 POST REST API - Axios 回傳為 Promise,可使用
try catch
做 error handling
API Function
App.vue
<template>
<input type="text" v-model="newTodo" />
<button @click="onAdd">Add</button>
</template>
<script setup>
import { ref } from 'vue'
import { addTodo } from '@/api/todos.js'
let newTodo = ref('')
let onAdd = async () => {
if (newTodo.value === '') return
await addTodo(newTodo.value)
newTodo.value = ''
}
</script>
Line 8
import { addTodo } from '@/api/todos.js'
- 從
api
目錄引用todos.js
內的addTodo()
Line 12
let onAdd = async () => {
if (newTodo.value === '') return
await addTodo(newTodo.value)
newTodo.value = ''
}
- 呼叫
addTodo()
API function,並將新增的 todo 傳入
todos.js
import axios from 'axios'
export let addTodo = async (todo) => {
let url = 'http://localhost:3000/todos'
let body = {
isCompleted: false,
todo
}
try {
let { data } = await axios.post(url, body)
return data
} catch (e) {
console.error(e)
}
}
Line 1
import axios from 'axios'
- 引用 Axios
Line 3
export let addTodo = async (todo) => {
}
export
:將addTodo()
匯出,如此其他地方才能使用import
將此 function 匯入
Line 11
try {
let { data } = await axios.post(url, body)
return data
} catch (e) {
console.error(e)
}
axios.post()
所回傳的資料都放在data
property 下,可使用{ data }
直接 Object Destructure- 因為
addTodo()
是 function,所以要有回傳值,至於要不要接收回傳值則由使用端的.vue
決定
Conclusion
- 實務上不建議將呼叫 API 寫在
.vue
內,因為 API 常常會被不同 component 或 view 重複呼叫,建議獨立抽成 API function - 實務上不建議將 function 包在 Object,然後匯出 Object,而是單獨 export 出 function,如此有助於 Vite 的 Tree Shaking