You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apollo Client:Vue项目中如何从Promise提取数据?

Vue Apollo 查询获取实际数据的正确方式

你用await没生效的关键原因是**await必须放在async标记的函数内部使用**,另外要注意:Apollo的query返回的Promise解析后是一个封装对象,实际数据在这个对象的data属性里,不是直接返回数据本身。

下面是两种可行的解决方案:

1. Async/Await 写法

把包含查询逻辑的函数声明为async,比如在Vue组件的方法中:

async getFooData() {
  try {
    // 用await等待Promise解析,拿到封装后的结果对象
    const queryResult = await this.$apollo.query({
      query: gql.getFoo,
      variables: {
        foo: bar
      }
    });
    // 从结果对象中提取实际数据
    const actualData = queryResult.data;
    // 这里可以把数据赋值给组件的响应式变量,比如this.fooData = actualData
    console.log('获取到的数据:', actualData);
  } catch (err) {
    // 捕获并处理查询错误
    console.error('查询Foo数据失败:', err);
  }
}

如果是在Vue的生命周期钩子(比如created)里使用,同样可以把钩子声明为async:

async created() {
  await this.getFooData();
}

2. Promise 链式调用写法

如果不习惯用async/await,也可以用Promise的then方法处理:

this.$apollo.query({
  query: gql.getFoo,
  variables: {
    foo: bar
  }
})
.then(queryResult => {
  const actualData = queryResult.data;
  console.log('获取到的数据:', actualData);
  // 处理数据逻辑
})
.catch(err => {
  console.error('查询Foo数据失败:', err);
});

内容的提问来源于stack exchange,提问作者abc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 18:52:15