【问题标题】:Nuxt Server Side Fetch & Internal Links Best PracticesNuxt 服务器端获取和内部链接最佳实践
【发布时间】:2022-01-05 11:21:39
【问题描述】:

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

当页面刷新(或第一次加载)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> 可用于外部链接。所以我想知道如果我们使用内部链接会有什么缺点(只是为了刷新页面并确保在服务器端获取)

或者有什么更好的方法可以在我们导航时始终获取服务器端?

【问题讨论】:

    标签: javascript frontend nuxt.js server-side-rendering nuxt-link


    【解决方案1】:

    这就是我处理它的方式,并始终使用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
      }
    },
    

    【讨论】:

    • 谢谢,但我听不懂。即使我们使用 fetch,第一行“process.server”总是返回 false(假设我们点击了内部 nuxt-link)并且它会从客户端发送请求,对吧?
    • ssr / process.server 仅在直接点击或页面刷新时发生,当您单击 nuxt 链接时,它始终在客户端呈现
    • 是的,这正是我想要解决的问题。我想在服务器端进行每次调用以使其更加私密。我能想到的唯一方法是使用 标记而不是 nuxt-link 但由于 nuxt 文档不建议将其用于内部链接
    猜你喜欢
    • 2010-12-21
    • 1970-01-01
    • 2018-03-06
    • 2012-10-07
    • 2012-09-13
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多