简体   繁体   中英

fetch Data during the generation in Nuxt 3

How can I get data only while generating a static page in Nuxt3. After generation, the data should be stored in the source code, ie the fetch command should be replaced by the fetched object. How is it possible in Nuxt3?

<template>
  <main>
    {{ page.content }
  </main>
</template>

<script setup>

const { data: page } = await useFetch(`http://api.example/pages/index`, { headers: { 'api-key': api.key }});

</script>

You can just run npm run generate , this will make the API call and build the page with all data during the build.

In .output/public/index.html you now see everything in there. You can now host this folder on any hosting site.

In an alternative, you can run npm run preview this will spin up a server with the index.html file, and you can right-click and check the page source.

There's also manual pre-rendering by adding this to nuxt.config.ts

pre rendering docs

  nitro: {
     prerender: {
        routes: ['/user/1', '/user/2']
     }
  }

Please have a look at the documentation on Nuxt website

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM