0

我正在使用 NuxtJS fetch()挂钩从 REST 服务获取异步数据。以下是请求

async fetch() {
  let response = await this.$axios.$get(`http://localhost:8080/app-server/v1/post/id/${this.$route.params.id}`);
}

我还需要发送一个可选的查询参数uid,即用户登录时的用户 ID。用户 ID 存储在 Vuex 状态中,可以在客户端访问,如下所示

this.$store.state.user.userDetails.id

但是当页面重新加载并在服务器端执行fetch()时,这将返回null。我也在寻找一种在服务器端访问此状态的方法。我尝试使用如下 Nuxt 上下文,但在服务器端运行时this.$nuxt.context它也返回null 。

this.$nuxt.context.store.state.user.userDetails.id

任何建议如何在服务器端访问 Vuex 状态。谢谢

4

1 回答 1

0

有一个预定义的方法 nuxtServerInit 您可以在您的商店中使用它来获取用户 ID 到服务器端的 vuex,然后再获取数据。https://hashinteractive.com/blog/using-nuxtserverinit-in-vuex-to-fetch-component-data/

然后您可以在 fetch 方法中从存储中检索它。Nuxt 2.12.2:使用新的 fetch 方法填充存储

于 2020-06-25T11:28:36.813 回答