在vue应用程序中,当用户单击按钮时,我需要运行gql查询。所以HTML部分有一个按钮:
<div
:id="'button-' + id"
class="more-button"
@click="showDetails(id)"> </div>
相应的函数执行一些调试console.log
并触发this.apollo.query
。问题是我可以在控制台中看到所有的console.log输出,所以函数会执行,但是没有出现钩子:error/result/watchLoading.至少我在控制台输出中没有看到任何东西。
showDetails(item) {
console.log("before: " + msid);
let msid = this.position.instrument.morningstarId;
this.xxx = msid;
this.$apollo.query({
query: GET_INSTRUMENT,
variables: {
morningstarId: this.position.instrument.morningstarId
},
result({ data }) {
console.log("L data: " + JSON.stringify(data));
},
error(error) {
alert("L We've got an error!" + JSON.stringify(error));
},
watchLoading(isLoading) {
console.log("L isLoading: " + isLoading);
}
});
console.log("after: " + msid);
}
当我将this.$apollo.query
的所有内容移动到组件中的apollo
部分时,一切正常。因此,更改后的工作代码如下所示:
...
data() {
return {
instrument: null
};
},
apollo: {
instrument: {
query: GET_INSTRUMENT,
variables() {
return {
morningstarId: this.position.instrument.morningstarId
};
},
result({ data }) {
console.log("G data: " + JSON.stringify(data));
},
error(error) {
alert("G We've got an error!" + JSON.stringify(error));
},
watchLoading(isLoading) {
console.log("G isLoading: " + isLoading);
}
}
},
computed
...
但我不希望在构建组件时调用此查询。我只想从函数中调用它。我对像描述的here那样使用skip()
方法作为解决方案不感兴趣。
问题是:我做错了什么,任何watchLoading/error/result钩子都将任何内容记录到控制台?
控制台中没有错误,也没有警告。但如果在示例中通过更改以下内容来实现强制错误:
this.$apollo.query({
query: GET_INSTRUMENT,
至
this.$apollo.query({
q_uery: GET_INSTRUMENT,
然后我在控制台中看到:
QueryManager.js?96af:473未捕获错误:查询选项是必需的。必须在查询选项中指定GraphQL文档。
所以我确信阿波罗正在处理这个查询。但我不知道如何访问结果或状态。
发布于 2018-08-06 06:05:33
解决方案是像对待Promise一样对待query
,并在其上使用then
方法。
如前所述,here:Promise对象表示异步操作的最终完成(或失败)及其结果值。
因此,我没有使用我使用的代码:
showDetails(item) {
console.log("before: " + msid);
let msid = this.position.instrument.morningstarId;
this.xxx = msid;
this.$apollo.query({
query: GET_INSTRUMENT,
variables: {
morningstarId: this.position.instrument.morningstarId
},
result({ data }) {
console.log("L data: " + JSON.stringify(data));
},
error(error) {
alert("L We've got an error!" + JSON.stringify(error));
},
watchLoading(isLoading) {
console.log("L isLoading: " + isLoading);
}
});
console.log("after: " + msid);
}
用于访问结果和处理错误的工作代码是
showDetails(item) {
this.$apollo
.query({
query: GET_INSTRUMENT,
variables: {
morningstarId: this.instrumentObj.instrument.morningstarId,
freq: this.chartFrequency
}
})
.then(data => {
this.instrument = data.data.instrument;
this.loading = data.loading;
this.networkStatus = data.networkStatus;
this.generatePastChart();
})
.catch(error => {
this.error = error;
alert("E " + error);
});
}
then
方法使用检索到的数据对象注册一个回调函数作为输入参数。
catch
会处理故障
https://stackoverflow.com/questions/51521379
复制相似问题