Vue 3 Data Fetching with Composables
ฟังก์ชัน Composable ที่สามารถนำกลับมาใช้ซ้ำได้สำหรับการดึงข้อมูลในแอปพลิเคชัน Vue 3
Vue 3 Data Fetching with Axios
การใช้ไลบรารี Axios สำหรับการทำ HTTP requests ใน Vue 3 Composables
js
import { ref, onMounted } from 'vue'
import axios from 'axios'
export function useAxiosFetch(url) {
const data = ref(null)
const error = ref(null)
const loading = ref(true)
const fetchData = async () => {
loading.value = true
try {
const response = await axios.get(url)
data.value = response.data
} catch (err) {
error.value = err
} finally {
loading.value = false
}
}
onMounted(fetchData)
return { data, error, loading, refetch: fetchData }
}
Vue 3 Data Fetching with ofetch
การใช้ ofetch ซึ่งเป็นตัวห่อ API fetch ที่มีขนาดเล็กใน Vue 3 Composables
js
import { ref, onMounted } from 'vue'
import { ofetch } from 'ofetch'
export function useOfetch(url) {
const data = ref(null)
const error = ref(null)
const loading = ref(true)
const fetchData = async () => {
loading.value = true
try {
data.value = await ofetch(url)
} catch (err) {
error.value = err
} finally {
loading.value = false
}
}
onMounted(fetchData)
return { data, error, loading, refetch: fetchData }
}