nuxt3 composables $fetch
时间: 2024-05-03 11:22:17 浏览: 84
0708 nuxt useFetch生产报错
Nuxt.js 3 is an upcoming version of the popular Vue.js-based framework that provides a lot of powerful features. One of the new features introduced in Nuxt.js 3 is the composables API, which allows developers to create reusable logic that can be used across multiple components.
One of the composables available in Nuxt.js 3 is `$fetch`. This composable provides a way to fetch data from an API endpoint using the Fetch API.
To use `$fetch`, you need to import it from `@nuxtjs/composition-api` and then call it in your component. Here's an example:
```
<template>
<div>
<h1>Posts</h1>
<ul>
<li v-for="post in posts" :key="post.id">{{ post.title }}</li>
</ul>
</div>
</template>
<script>
import { ref } from '@nuxtjs/composition-api';
export default {
setup() {
const posts = ref([]);
const fetchPosts = async () => {
const response = await $fetch('https://jsonplaceholder.typicode.com/posts');
posts.value = await response.json();
};
fetchPosts();
return {
posts,
};
},
};
</script>
```
In this example, we import `ref` from `@nuxtjs/composition-api` and use it to define a reactive `posts` variable. We then define a function called `fetchPosts` that calls `$fetch` to fetch data from the API endpoint and updates the `posts` variable. Finally, we call `fetchPosts` in the `setup` function and return `posts` as a property of the component.
Note that `$fetch` is only available in components that use the `setup` function, which is a new syntax introduced in Nuxt.js 3. Also, `$fetch` only works with server-side rendering (SSR) and cannot be used in client-only components.
阅读全文