nuxt3 $fetch
时间: 2023-12-31 21:04:21 浏览: 89
nuxt-new-fetch-example:nuxt新的获取api示例
Nuxt3 $fetch is a new method introduced in Nuxt3 which allows you to fetch data from an external API or server-side rendered (SSR) page. It replaces the $axios module used in Nuxt2.
$fetch is a lifecycle hook that is called before the component is rendered. It can be used to fetch data and then render the component with the fetched data.
Here is an example of how to use $fetch in Nuxt3:
```javascript
<script>
export default {
async $fetch() {
const response = await fetch('https://example.com/api/data')
const data = await response.json()
return { data }
},
data() {
return {
data: {}
}
}
}
</script>
<template>
<div>
<p>{{ data }}</p>
</div>
</template>
```
In this example, $fetch is used to fetch data from an external API and then the data is stored in the component's data object.
Note that $fetch is an asynchronous method and it must return a Promise or resolve with the fetched data.
阅读全文