抽取成一个组合式函数:
javascript
// fetch.js
//接收响应式状态
import { ref, watchEffect, toValue } from 'vue'
//一个封装的异步请求
import { fetch } from '../XX'
export function useFetch(url) {
const data = ref(null)
const error = ref(null)
const fetchData = () => {
// 重置data,error 数据
data.value = null
error.value = null
//toValue() 是一个在 3.3 版本中新增的 API。它的设计目的是将 ref 或 getter 规范化为值
fetch(toValue(url))
.then((res) => res.json())
.then((json) => (data.value = json))
.catch((err) => (error.value = err))
}
watchEffect(() => {
//只要fetchData函数中的url变就自动触发watchEffect
fetchData()
})
return { data, error }
}
在组件里只需要这样使用:
javascript
<script setup>
import { useFetch } from './fetch.js'
// 当 props.id 改变时重新 fetch
const { data, error } = useFetch(() => `/posts/${props.id}`)
</script>