0

我在这个项目中使用 nuxt、wordpress graphql 和 apollo。我正在尝试在我的 CategoryProps.vue 文件中编写一个 Show More 按钮。我有一个 weight-loss.vue 页面,它将类别传递给 CategoryProps.vue 组件内的 apollo 查询变量“$category”。

从一开始就自动显示三个帖子,单击“显示更多”按钮将呈现另外 3 个帖子。

我不断收到“传播不可迭代实例的无效尝试。为了可迭代,非数组对象必须具有 Symbol.iterator 方法”错误。

/CategoryProps.vue

export default {
  props: {
    chosenCategory: {
      type: String,
      default: ''
    }
  },

  data() {
    return {
      category: [],
      postQuantity: 3,
      showMoreEnabled: true
    }
  },

  apollo: {
    category: {
      prefetch: true,
      query: ArticlesByCategoryQuery,
      variables() {
        return {
          category: this.chosenCategory,
          first: this.postQuantity,
          after: null
        }
      }
    }
  },

  methods: {
    showMore() {
      this.$apollo.queries.category.fetchMore({
        variables: {
          first: this.postQuantity,
          after: null
        },

        updateQuery: (existing, { fetchMoreResult }) => {
          if (!fetchMoreResult) return existing

          const hasMore = fetchMoreResult.category.posts.pageInfo.hasNextPage

          this.showMoreEnabled = hasMore

          console.log(fetchMoreResult.category.posts.pageInfo.endCursor)
          console.log(existing.category.__typename)

          return {
            ...existing,
            category: {
              ...existing.category,
              // Update the cursor
              after: fetchMoreResult.category.posts.pageInfo.endCursor,

              // Combine incoming posts to existing posts
              posts: [
                ...existing.category.posts,
                ...fetchMoreResult.category.posts
              ],
              hasMore
            }
          }
        }
      })
    }
  }
}
</script>

/myquery.gql

query MyQuery($category: ID!, $first: Int!, $after: String) {
  category(id: $category, idType: NAME) {
    posts(first: $first, after: $after) {
      edges {
        cursor
        node {
          slug
          id
          title
          featuredImage {
            node {
              sourceUrl
              altText
            }
          }
        }
      }
      pageInfo {
        endCursor
        hasNextPage
      }
    }
    name
    id
  }
}

//减肥.vue

<CategoryProps chosenCategory="Weight Loss" />
4

0 回答 0