Nuxt JS Apollo data only available after page refresh

后端 未结 2 1306
北海茫月
北海茫月 2021-01-02 22:26

I am fetching some data using Apollo inside of Nuxt. Somehow, when navigating to that page I get an error of

Cannot read property \'image\' of undefined


        
相关标签:
2条回答
  • 2021-01-02 22:38

    I think it's only a problem of timing on page load.

    You should either iterate on products, if you have more than one, or have a v-if="product != null" on a product container, that will render only once the data is fetched from GraphQL.

    In that way you'll use the object in your HTML only when it's really fetched and avoid reading properties from undefined.

    0 讨论(0)
  • 2021-01-02 22:50

    I stumbled on this issue as well, and found it hidden in the Vue Apollo documents.

    Although quite similar to the OP's reply, it appears the official way is to use the "$loadingKey" property.

    It's quite confusing in the documents because there are so many things going on. https://vue-apollo.netlify.com/guide/apollo/queries.html#loading-state

    <template>
      <main
        v-if="!loading"
        class="my-8 mb-4"
      >
        <div class="w-3/4 mx-auto mb-16">
          <h2 class="mx-auto text-4xl text-center heading-underline">
            {{ page.title }}
          </h2>
          <div
            class="content"
            v-html="page.content.html"
          ></div>
        </div>
      </main>
    </template>
    
    <script>
    import { page } from "~/graphql/page";
    
    export default {
      name: 'AboutPage',
    
      data: () => ({
        loading: 0
      }),
    
      apollo: {
        $loadingKey: 'loading',
        page: {
          query: page,
          variables: {
            slug: "about"
          }
        },
      }
    }
    </script>
    

    If you need to use a reactive property within vue such as a slug, you can do so with the following.

    <template>
      <main
        v-if="!loading"
        class="my-8 mb-4"
      >
        <div class="w-3/4 mx-auto mb-16">
          <h2 class="mx-auto text-4xl text-center heading-underline">
            {{ page.title }}
          </h2>
          <div
            class="content"
            v-html="page.content.html"
          ></div>
        </div>
      </main>
    </template>
    
    <script>
    import { page } from "~/graphql/page";
    
    export default {
      name: 'AboutPage',
    
      data: () => ({
        loading: 0
      }),
    
      apollo: {
        $loadingKey: 'loading',
        page: {
          query: page,
          variables() {
            return {
              slug: this.$route.params.slug
            }
          }
        },
      }
    }
    </script>
    
    0 讨论(0)
提交回复
热议问题