axios.get()
可簡單呼叫 GET REST API。
Version
Vue 3.4
Axios 1.6.7
GET
<template>
<ul>
<li v-for="item in todos" :key="item.id">
{{ item.todo }}
</li>
</ul>
</template>
<script setup>
import axios from 'axios'
import { ref, onMounted } from 'vue'
let todos = ref([])
onMounted(async () => {
let url = 'http://localhost:3000/todos'
try {
let { data } = await axios.get(url)
todos.value = data
} catch (e) {
console.error(e)
}
})
</script>
Line 2
<ul>
<li v-for="item in todos" :key="item.id">
{{ item.todo }}
</li>
</ul>
v-for
:列舉todos
state
Line 10
import axios from 'axios'
- 引用 Axios
Line 13
let todos = ref([])
todos
state:儲存所有 todo
Line 15
onMounted(async () => {
let url = 'http://localhost:3000/todos'
try {
let { data } = await axios.get(url)
todos.value = data
} catch (e) {
console.error(e)
}
})
onMounted()
:呼叫 GET REST API function 取得所有 todos- 將
url
傳入axios.get()
呼叫 GET REST API axios.get()
所回傳的資料都放在data
property 下,可使用{ data }
直接 Object Destructure- Axios 回傳為 Promise,可使用
try catch
做 error handling
API Function
App.vue
<template>
<ul>
<li v-for="item in todos" :key="item.id">
{{ item.todo }}
</li>
</ul>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { getTodos } from '@/api/todos.js'
let todos = ref([])
onMounted(async () => (todos.value = await getTodos()))
</script>
Line 8
import { getTodos } from '@/api/todos.js'
- 從
api
目錄引用todos.js
內的getTodos()
Line 15
onMounted(async () => (todos.value = await getTodos()))
- 呼叫
getTodos()
API function 取得所有 todos
todos.js
import axios from 'axios'
export let getTodos = async () => {
let url = 'http://localhost:3000/todos'
try {
let { data } = await axios.get(url)
return data
} catch (e) {
console.error(e)
}
}
Line 1
import axios from 'axios'
- 引用 Axios
Line 3
export let getTodos = async () => {
}
export
:將getTodos()
匯出,如此其他地方才能使用import
將此 function 匯入
Line 6
try {
let { data } = await axios.get(url)
return data
} catch (e) {
console.error(e)
}
axios.get()
所回傳的資料都放在data
property 下,可使用{ data }
直接 Object Destructure- 因為
getTodos()
是 function,所以要有回傳值,至於要不要接收回傳值則由使用端的.vue
決定
Conclusion
- 實務上不建議將呼叫 API 寫在
.vue
內,因為 API 常常會被不同 component 或 view 重複呼叫,建議獨立抽成 API function - 實務上不建議將 function 包在 Object,然後匯出 Object,而是單獨 export 出 function,如此有助於 Vite 的 Tree Shaking