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

Vue3组合式API中setup内绑定点击的异步函数无法触发是什么原因?

问题原因&修复方案


1. 核心触发失败原因

你在setup()函数中定义的callApi方法没有显式返回,Vue 3规定setup内部定义的变量、方法如果要在模板中使用,必须通过return暴露给模板,否则模板绑定的@click="callApi"找不到对应的处理函数,点击自然没有反应。

2. 其他隐藏问题

  • 你用普通const定义的apiMessage、executed不是响应式变量,后续赋值后模板不会同步更新渲染,需要用ref包裹
  • 变量名拼写错误:你inject拿到的是小写auth变量,后续调用写的是大写Auth.getTokenSilently(),会抛出未定义错误
  • Fauna导入错误:你当前从faunadb导入的是小写client,但代码中要实例化的是构造函数Client,大小写不匹配会报错

修复后的逻辑代码

import { defineComponent, inject, ref } from "vue";
// 修正导入,引入构造函数Client
import { query as q, Client } from "faunadb";

export default defineComponent({
  name: "Api",
  setup() {
    console.log("Setup is working");
    // 定义响应式变量
    const apiMessage = ref(null);
    const executed = ref(false);

    const callApi = async () => {
      console.log("callApi is working");
      // 修正变量名,使用inject拿到的小写auth
      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);
        // ref变量赋值需要访问.value属性
        apiMessage.value = data;
        executed.value = true;
      } catch (e) {
        console.log(e);
        apiMessage.value = `Error: the server responded with '${e.response?.status}: ${e.response?.statusText}'`;
      }
    };

    // 把模板要用到的方法、变量显式return出去
    return {
      callApi,
      apiMessage,
      executed
    }
  },
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 22:18:03