问题描述
我正在尝试使用Vue Apollo查询单个产品,但我不明白我在做什么错。在控制台中,出现以下错误:Observable.js?a7b2:65 Uncaught TypeError: Cannot read property 'product' of undefined
查询:
export const getProduct = gql`
query getProduct ($productId: ID!) {
product (where: {id: $productId}) {
id
title
description
price
productDetails {
html
}
productAssets {
id
url
}
}
}
`;
组件:
apollo: {
$loadingKey: 'loading',products: {
query: getProduct,variables: {
$productId: 'ABC123',},result ({data}) {
this.loading = false;
this.product = data.product;
this.assets = data.assets;
},error () {
this.error = true;
this.sentryError = error;
},
如果我将ID硬编码在其中,则可以使用。
export const product = gql`
query getProduct ($product: ID!) {
product (where: {id: "ABC123"}) {
id
title
description
price
productDetails {
html
}
productAssets {
id
url
}
}
}
`;
我看不到我所缺少的东西,任何帮助将不胜感激。
解决方法
首先,可能需要参数。您将$product: ID!
(由!
设置为必填项。
Playground
-运行查询的选项:
1。通过“硬代码”进行查询
“如果我将ID硬编码在其中,则可以使用”
这是第一种方式(您在查询中手动声明参数)。
2。 “查询变量”标签
点击[查询变量],然后以 JSON 格式传递vars变量。
graphql-variables额外阅读:
Vue-查询参数:
// Apollo-specific options
apollo: {
// Query with parameters
ping: {
// gql query
query: gql`query PingMessage($message: String!) {
ping(message: $message)
}`,// Static parameters
variables: {
message: 'Meow',},
https://apollo.vuejs.org/guide/apollo/queries.html#query-with-parameters