获取数据
获取数据
重新调用API
方式一
const xxxx = ref("")
const {data,status} = await useFetch(
()=> `https://xxxxx?q=${xxxx.value}`,
{
lazy:true
}
)
方式二
const xxxx = ref("")
const url = computed( ()=> `https://xxxxx?q=${xxxx.value}`)
const {data,status} = await useFetch(
url,
{
lazy:true
}
)
方式三(推荐)
const xxxx = ref("")
const {data,status} = await useFetch(
'https://xxxxx',
{
lazy:true
query:{
// 注意这里不能用xxxx.value
q:xxxx
}
}
)
重新获取数据
const xxxx = ref("")
const {data,status,execute} = await useFetch(
'https://xxxxx',
{
lazy:true
query:{
// 注意这里不能用xxxx.value
q:xxxx
}
}
)
...
<UButton @click="execute">Refresh Data</UButton>
错误处理
客户端
const {data,status,error} = await useFetch(....)
// 到客户端这边需要一直监控者
watchEffect(()=>{
if(error.value){
throw createError({...error.value,fatal:true})
}
})
并行请求
const {data} await useAsyncData(()=>{
return Promise.all([
$fetch('url1'),
$fetch('url2')
])
})
const author = computed(()=>data.value?.[0])
const comments = computed(()=>data.value?.[1])
获取缓存数据
方式一
const { data } = await useFetch('/api/randomUser', {
getCachedData(key,nuxtApp) {
const data = nuxtApp.payload.data[key]||nuxtApp.static.data[key]
return data;
},
})
设定过期时间
const { data } = await useFetch('/api/randomUser', {
transform(data){
return {
...data,
expiresAt: Date.now() + 10_000
}
},
getCachedData(key,nuxtApp) {
const data = nuxtApp.payload.data[key]||nuxtApp.static.data[key]
if(Date.now() >= data?.expiresAt) return undefined;
return data;
},
})
指定返回内容
方式一
const { data } = await useFetch<{
lastName: string;
firstName: string;
}>('https://xxxxx',{
pick:['aaa','bbb']
});
方式二
返回对象
const { data } = await useFetch<{
users: {
lastName: string;
firstName: string;
}[]
}>('https://xxxxx',{
transform(data) {
return {
users: data.users.map((user) => {
return {
firstName: user.firstName,
lastName: user.lastName
}
})
}
});