Nuxt JS Apollo数据仅在页面刷新后可用 [英] Nuxt JS Apollo data only available after page refresh

查看:239
本文介绍了Nuxt JS Apollo数据仅在页面刷新后可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Nuxt内部使用Apollo获取一些数据.不知何故,导航到该页面时出现错误

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

刷新页面后,一切都会按预期进行.

When I refresh the page, everything works as expected.

我发现有一些类似问题的人,但是似乎没有解决方案对我有用:/

I have a found a few threads of people having similar issues but no solution seems to work for me :/

这是我的模板文件:

/products/_slug.vue

/products/_slug.vue

<template>
  <section class="container">
    <div class="top">
      <img :src="product.image.url"/>
      <h1>{{ product.name }}</h1>
    </div>
  </section>
</template>

<script>
import gql from 'graphql-tag'

export default {
  apollo: {
    product: {
      query: gql`
        query Product($slug: String!) {
          product(filter: { slug: { eq: $slug } }) {
            slug
            name
            image {
              url
            }
          }
        }
      `,
      prefetch({ route }) {
        return {
          slug: route.params.slug
        }
      },
      variables() {
        return {
          slug: this.$route.params.slug
        }
      }
    }
  }
}
</script>

基本上,除非刷新页面,否则$ apolloData保持为空.任何想法将不胜感激

Basically the $apolloData stays empty unless I refresh the page. Any ideas would be much appreciated

编辑 走近了一步(我认为).以前,第一次导航到页面时,所有内容(image.url和名称)都将是不确定的.

EDIT Got one step closer (I think). Before, everything (image.url and name) would be undefined when navigating to the page for the first time.

我添加了:

data() {
    return {
      product: []
    };
  }

在导出的顶部,现在至少总是定义名称,因此,如果我删除图像,一切都会按预期进行.只是image.url一直未定义.

at the top of my export and now at least the name is always defined so if I remove the image, everything works as expected. Just the image.url keeps being undefined.

我注意到的一件事(不确定相关性)是仅使用会发生此问题,如果我使用正常的标签,它会起作用,但当然会消除vue的魔力.

One thing I noticed (not sure how relevant) is that this issue only occurs using the , if I use a normal a tag it works but of course takes away the vue magic.

EDIT-2 所以以某种方式,如果我将Nuxt降级到1.0.0版本,一切都很好

EDIT-2 So somehow if I downgrade Nuxt to version 1.0.0 everything works fine

推荐答案

我认为这只是页面加载时间的问题.

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

如果有多个产品,则应该迭代产品,或者在产品容器上具有v-if="product != null",只有从GraphQL提取数据后,该容器才会呈现.

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.

通过这种方式,只有在真正获取HTML时,才在HTML中使用该对象,并避免读取未定义的属性.

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

这篇关于Nuxt JS Apollo数据仅在页面刷新后可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆