我使用的是Vue 2和组合API.我当前的组件从父级接收props ,并根据它在屏幕上呈现不同的数据-props 称为"Result",类型为Object,包含多个信息.我一次只收到一个"结果",但会呈现多个结果--您可以将我的"结果"视为Google搜索结果--这意味着页面将有多个结果.

我的问题是,对于"Result"中的一个信息,我需要调用一个异步方法并显示其结果,这是我无法完成的.

目前我所拥有的是:

<div>
   {{ getBoardName(props.result.boardReference) }}
</div>

脚本中的方法:

async function getBoardName(boardReference) {
  var result = await entriesApi.getBoardName({
    boardReference: boardReference,
  });
  return result;
}

它显示"[Object Promise]",尽管如果我在返回它之前对其进行sole.log(Result),这正是我需要的,所以在我看来,插补实际上并不等待Promise结果.

我还try 在插值法中使用"THEN":

{{
  getBoardName(props.result.boardReference).then((value) => {
    return value;
   })
}}

我正在考虑使用计算(computed)属性,但我不确定这将如何工作,因为我需要从该方法获得的响应必须单独连接到每个结果.

如有需要,请要求进一步澄清.

推荐答案

As you thought, the interpolation does not actually wait for the result so this is why you have a Promise object.

Since you are using the composition API, what you can actually do is to use a reactive state (using the ref() function if you are waiting for a primitive type, which seems to be the case here, or the reactive() function for objects) and update the state within the onMounted() lifecycle hook.

setup(props, context) {
  const boardGameName = ref("");

  onMounted(async () => {
    boardGameName.value = await getBoardName(props.result.boardReference);
  });

  async function getBoardName(boardReference) {
    var result = await entriesApi.getBoardName({
      boardReference: boardReference,
    });
    return result;
  }

  return {
    boardGameName,
  };
}

Since you are dealing with async data, you could add a loading state so you can show a spinner or something else until the data is available.
If your board reference changes over time, you could use a watcher to update your board game name.

Good luck with your project!

Javascript相关问答推荐

原型链中的同一财产怎么会有不同的价值?

如何从JavaScript中的公共方法调用私有方法?

我可以后增量超过1(最好是内联)吗?

如果没有尾随斜线,托管在收件箱中的React/Vite将无法工作

创建私有JS出口

如何解决chrome—extension代码中的错误,它会实时覆盖google—meet的面部图像?'

MongoDB中的引用

Google maps API通过API返回ZERO_RESULTS,以获得方向请求,但适用于Google maps

无法从NextJS组件传递函数作为参数'

PDF工具包阿拉伯字体的反转数字

S文本内容和值不必要的不同

在Matter.js中添加从点A到另一个约束的约束

VSCode中出现随机行

Nextjs 13.4 Next-Auth 4.2登录(&Quot;凭据&,{});不工作

自定义图表工具提示以仅显示Y值

传递方法VS泛型对象VS事件特定对象

为列表中的项目设置动画

更改agGRID/Reaction中的单元格格式

用于测试其方法和构造函数的导出/导入类

JavaScript&;Reaction-如何避免在不使用字典/对象的情况下出现地狱?