Nuxt 服务器端获取和内部链接最佳实践



我想始终在服务器端获取数据(为了防止它们可以从网络选项卡中读取(

当页面刷新(或第一次加载(时,process.server返回true,在网络选项卡上看不到任何内容。

async asyncData({ params, $axios }) {
console.log(process.server)
const { id } = params;
const url = `api/post/${params.id}`
const post = await $axios.$get(url);
return { post };
}

然而,当我尝试使用router-linknuxt-link通过内部链接导航时,总是以客户端获取结束。process.server返回false,在网络选项卡上可以看到请求/响应。

我提出的唯一解决方案是使用<a>而不是内部链接,多亏了这个页面,我们可以在服务器端获取。

Nuxt文档表示,内部链接总是使用nuxt-link而不是<a>,但<a>可以用于外部链接。所以我想知道如果我们使用内部链接(只是为了刷新页面并确保在服务器端获取(会有什么缺点

或者,当我们导航时,有没有更好的方法来获取服务器端?

这就是我处理它并在整个过程中使用nuxt-link的方法。

使用fetch钩子,然后在两者上都调用它。

async fetch() {
this.getItems()
},

此外,如果您愿意,可以通过this.$root.context.ssrContext直接调用服务器端代码,这与您在商店中使用nuxtServerInit时所做的事情相同。

async fetch() {
if (process.server) {
let items = []
if (this.isset(this.$root, 'context.ssrContext.req.thingsModel')) {
items = this.$root.context.ssrContext.req.cache.get('things', [])
if (!items.length) {
items = await this.$root.context.ssrContext.req.thingsModel.get(
this.limit
)
items = this.$copy(items)
this.$root.context.ssrContext.req.cache.put('things', items, 60000 * 60)
}
}
this.items = items
} else {
this.getItems() // would be an ajax call to populate items
}
},

最新更新