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

Nuxt 3 集成nuxt/apollo:点击按钮无法调用mutate函数

Nuxt 3 + Apollo 登录Mutation点击无响应问题修复

问题核心原因

你的代码存在三个关键问题导致按钮触发无响应:

  1. 表单输入未同步到请求变量:输入框绑定formData,但请求时用硬编码的variables,虽不是无响应的直接原因,但会导致请求数据错误。
  2. 缺少错误捕获机制:异步函数onSubmit未处理login调用可能抛出的错误,出错时无任何反馈,看起来像未执行。
  3. SSR环境限制:页面加载时调用onSubmit是在SSR阶段执行,但按钮点击是客户端操作,若客户端Apollo实例未正确初始化,会导致Mutation无法执行。

修复步骤及完整代码

1. 同步表单输入到请求变量

将请求变量改为动态获取表单输入值,确保使用用户实际输入的账号密码。

2. 添加错误捕获

在异步函数中加入try/catch,捕获并处理请求错误,同时给用户反馈。

3. 限制客户端执行

通过process.client确保Mutation只在客户端环境执行,避免SSR阶段的兼容性问题。

<template>
    <div class="h-screen flex items-center justify-center w-full">
        <form class="w-1/3" @submit.prevent="onSubmit">
            <div class="p-5">
                <h1>Login</h1>
            </div>
            <div class="p-5">
                <input type="email" id="email" name="email" placeholder="E-Mail" class="input w-full"
                    v-model="formData.email" />
            </div>
            <div class="p-5">
                <input type="password" id="password" name="password" placeholder="Password" class="input w-full"
                    v-model="formData.password" />
            </div>
            <div class="p-5">
                <button type="submit" class="btn bg-violet-700">Login</button>
            </div>
        </form>
        {{ res }}
    </div>
</template>

<script setup lang="ts">
const formData = ref({
    email: '',
    password: ''
})

const res = ref('')

const mutation = gql`
    mutation Login($email: String!, $password: String!, $device_name: String! = "web") {
        login(email: $email, password: $password, device_name: $device_name) 
    }
`

const { mutate: login } = useMutation(mutation)

// 动态生成请求变量
const getRequestVariables = () => ({
    email: formData.value.email,
    password: formData.value.password
})

const onSubmit = async () => {
    // 仅在客户端执行Mutation
    if (!process.client) return
    
    try {
        const response = await login(getRequestVariables())
        res.value = response?.data.login || '登录成功'
    } catch (error) {
        console.error('登录请求失败:', error)
        res.value = '登录失败,请检查账号密码或网络连接'
    }
}

// onSubmit()
</script>

<style scoped></style>

额外排查点

  • 打开浏览器控制台,查看是否存在跨域错误、GraphQL语法错误或Apollo客户端初始化报错。
  • 确认GraphQL API地址在客户端可访问(本地API需配置CORS)。
  • 检查按钮是否被其他元素遮挡,导致无法触发点击事件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 08:06:12