本文介绍了如何在没有 API 请求的情况下使用 Nuxt.js 生成 100% 静态网站?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用

如果有人有更好的解决方案,请分享,我很乐意接受该答案作为正确答案:)

I am testing around with Nuxt.js to generate a static website.

Is it possible to generate a 100% static site when using an API to fetch data, so that one can get rid of the API and requests?

Based on my tests so far that all the files are generated properly and being hosted on the Github Pages and can be reached, except:

  1. When hitting the pages directly via URL bar, no error (expected behavior)
  2. When navigating to the pages via routes, the pages is still sending the request to API (does not exist outside local machine), even though the data has already been fetched and the .html file is generated with the data already during the generate process.

Using asyncData to get the data for the components from the API.

解决方案

The solution was to use vuex (state management) and populate the state with the data during the generation process.

The state will be already populated in the generated .html file

For more information please refer to the this thread where it is being discussed.

Example:

async fetch({ store }) {
  if (_.isEmpty(store.getters['tags/getTags'])) {
    await store.dispatch('tags/fetchTags');
  }
},

  • The fetch method is used to fill the store before rendering the page
  • fetchTags is the actions making a request to api and populate the state
  • The logic is quite simple: if the tags state is not already populated, then populate it by making a request to an api
  • When running nuxt generate the state will be populated for the deployment, hence to api request won't be sent
  • The state will be injected into the .html file (pic below for reference)

If anyone have a better solution, please share, I will gladly accept that answer as a correct one :)

这篇关于如何在没有 API 请求的情况下使用 Nuxt.js 生成 100% 静态网站?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 16:49