【问题标题】:How to set Nuxt SSR async metadata in a typescript class component? Fetching using Apollo如何在打字稿类组件中设置 Nuxt SSR 异步元数据?使用 Apollo 获取
【发布时间】:2022-01-16 13:57:36
【问题描述】:

我试图在获取数据后在 Nuxt 中设置页面元数据,但在类组件中这样做。更糟糕的是,我正在使用 Apollo 获取数据。有很多使用 asyncData 的示例,例如 heredocumentation 有关于获取的信息。但是,我发现 1) 我无法访问数据,或者 2) 如果在类组件中执行其中任何一项操作,我无法使用 this.$apollo.query。这是我到目前为止基于 SO 答案和文档的内容。

阿波罗的问题:

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'

@Component({
  head(): Record<string, unknown> {
    return { title: this.response.title }
  },
  async asyncData(): Promise<any> {
    const response = this.$apollo.query({ // <-- does't work
      query: SITE_PAGE,
      variables: {
        path: this.$route.path
      }
    });
    return { response }
  },
})
export default class StandardPage extends Vue {}
</script>

如果我只是点击服务器而不是 Apollo 来获取数据,那么访问数据就会出现问题:

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'

@Component({
  head(): Record<string, unknown> {
    return { title: this.response.title } // <-- cant access response below / undefined
  },
  async asyncData({ params, $http }) {
    const response = await $http.$get(`https://<myserverapi>/getpage`)
    console.log(response.title) // <--got data along with title
    return { response }
  }
})
export default class StandardPage extends Vue {}
</script>

谁能告诉我我做错了什么或者我还需要什么?

【问题讨论】:

    标签: typescript vue.js nuxt.js apollo server-side-rendering


    【解决方案1】:

    为了访问数据,您需要将:YOUR_CLASS_NAME 放在头构造函数中。

    为了使用 Apollo,您可以通过将上下文传递给 asyncData 来访问它。

    最终代码如下所示:

    <script lang="ts">
    import { Component, Vue } from 'vue-property-decorator'
    
    @Component({
      head(this: StandardPagePage): Record<string, unknown> { // <-- added this:StandardPage
        return { title: this.response.title }
      },
      async asyncData(context): Promise<any> { // <-- added context
    
        // call to Apollo now looks like this:
    
        const client = context.app.apolloProvider?.defaultClient
        const response = await client!.query({
          query: SITE_PAGE,
          variables: {
            path: context.route.path,
          },
        })
        return { response }
      },
    })
    export default class StandardPage extends Vue {}
    </script>
    

    【讨论】:

      猜你喜欢
      • 2021-08-17
      • 1970-01-01
      • 2023-02-25
      • 2020-04-11
      • 2021-06-02
      • 1970-01-01
      • 2016-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多