【问题标题】:Why won't my async call fire inside this Vue 3 component (using composition API)?为什么我的异步调用不会在这个 Vue 3 组件中触发(使用组合 API)?
【发布时间】:2021-11-30 14:27:58
【问题描述】:

我正在尝试进行异步调用以从我的 Fauna 数据库中获取数据。但我无法触发异步调用。

setup() 函数中,我有console.log("Setup is working");,它按预期工作。它会在页面加载时显示。

然后在 callApi 异步函数中我有 console.log("callApi is working");。在按钮单击事件上调用该异步函数。但是当点击按钮时没有任何反应。该函数没有被触发,并且没有任何内容打印到控制台。

我做错了什么?

<template>
  <div>
    <div class="mb-5">
      <button class="btn btn-primary mt-5" @click="callApi">
        Call API
      </button>
    </div>

    <div class="result-block-container">
      <div :class="['result-block', executed ? 'show' : '']">
        <h6 class="muted">Result</h6>
        {{ JSON.stringify(apiMessage, null, 2) }}
      </div>
    </div>
  </div>
</template>
import { defineComponent, inject } from "vue";
import { query as q, client } from "faunadb";

export default defineComponent({
  name: "Api",
  setup() {
    console.log("Setup is working"); //<---- THIS PRINTS TO CONSOLE ON PAGE LOAD
    const callApi = async () => {
      console.log("callApi is working"); //<---- THIS DOES NOT PRINT TO CONSOLE ON BUTTON CLICK
      const apiMessage = null;
      const executed = false;
      const auth = inject("Auth");
      const accessToken = await Auth.getTokenSilently();
      try {
        const client = new Client({ secret: accessToken });
        const { Paginate, Documents, Collection, Lambda, Get, Var } = q;

        const data = await client.query(
          q.Map(
            Paginate(Documents(Collection("stores"))),
            Lambda(["storeRef"], Get(Var("storeRef")))
          )
        );

        console.log(data);
        apiMessage = data;
        executed = true;
      } catch (e) {
        console.log(e);
        apiMessage = `Error: the server responded with '${e.response.status}: ${e.response.statusText}'`;
      }
    };
  },
});

【问题讨论】:

  • 你不需要return 来自setup() 的东西吗?
  • 是的!谢谢,就是这样 - 想添加它作为答案,我会接受吗?

标签: javascript vuejs3 vue-composition-api


【解决方案1】:

Usage with Templates

如果 setup 返回一个对象,则可以在组件的模板中访问该对象的属性

您只需要返回您希望模板可用的属性

return {
  callApi
}

【讨论】:

    猜你喜欢
    • 2021-02-24
    • 1970-01-01
    • 2020-12-20
    • 2020-07-02
    • 1970-01-01
    • 2016-06-20
    • 2022-01-26
    • 2020-02-26
    • 2021-01-24
    相关资源
    最近更新 更多