问题描述
我正在使用
如果有人有更好的解决方案,请分享,我很乐意接受该答案作为正确答案:)
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:
- When hitting the pages directly via URL bar, no error (expected behavior)
- 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% 静态网站?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!