【问题标题】:NuxtJS: How to access Vuex state on Server sideNuxtJS:如何在服务器端访问 Vuex 状态
【发布时间】:2020-06-25 07:54:07
【问题描述】:

我正在使用 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 状态的任何建议。谢谢

【问题讨论】:

  • 您的商店在页面刷新后被清除,因此没有数据。
  • @Ifaruki 用户信息也保存在 cookie 中。所以在页面刷新后从那里检索它。
  • 好的,你在哪里检索它/如何?

标签: vue.js vuejs2 nuxt.js server-side-rendering nuxtjs


【解决方案1】:

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

然后您可以在 fetch 方法中从 store 中检索它。 Nuxt 2.12.2: Filling the store with the new fetch method

【讨论】:

  • 但是在我们的例子中,登录用户的 ID 被保存到一个 cookie 中。因此,如果 Vuex 存储被页面重新加载清除,它会从 cookie 中获取并添加到存储中。我猜您的解决方案是从后端 API 获取数据并填充存储。但在我们的例子中,细节只在客户端,我们需要在服务器端渲染期间让它们在服务器上可用。
  • 您可以使用这些链接中的信息使其适用于您的解决方案。 nuxtServerInit({ dispatch }, { res }),然后从 res.body 中获取 cookie 并保存到 vuex。然后为用户信息创建 getter 并使用 this.$nuxt.context.store.getters 在您的 fetch 方法中调用它。
猜你喜欢
  • 1970-01-01
  • 2020-12-21
  • 2021-09-23
  • 2020-01-27
  • 2019-11-04
  • 2020-07-28
  • 1970-01-01
  • 2018-09-02
  • 1970-01-01
相关资源
最近更新 更多