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

Nuxt3中Google身份验证按钮data-callback未触发问题排查

Nuxt3中Google登录按钮data-callback不触发问题

我在Nuxt3项目中创建了signin.vue按钮组件,代码如下:

<template>
  <div
    id="g_id_onload"
    :data-client_id="config.public.GOOGLE_CLIENT_ID"
    data-context="signin"
    data-ux_mode="popup"
    :data-callback="googleCallback"
    data-auto_prompt="false"
  ></div>

  <div
    class="g_id_signin"
    data-type="standard"
    data-shape="rectangular"
    data-theme="outline"
    data-text="signin_with"
    data-size="large"
    data-logo_alignment="left"
    data-width="384"
  ></div>
</template>

<script setup>
const config = useRuntimeConfig();

const googleCallback = (response) => {
  console.log("Handle the response", response);
};

useHead({
  script: [
    {
      async: true,
      src: "https://accounts.google.com/gsi/client",
      defer: true,
    },
  ],
});
</script>

应用可正确渲染该按钮,我已按照Google官方指南完成相关操作步骤,但data-callback未触发,控制台也未显示对应信息,请问我哪里操作有误?


问题原因及解决办法

  • 回调函数需挂载到全局window对象
    Google登录脚本运行在全局环境,无法直接访问Vue组件内部的googleCallback函数。需将函数挂载到window上:

    const googleCallback = (response) => {
      console.log("Handle the response", response);
    };
    // 挂载到全局window
    window.googleCallback = googleCallback;
    

    同时模板里的:data-callback要改为字符串形式(Google脚本需要全局函数名,而非Vue响应式引用):

    <div
      id="g_id_onload"
      :data-client_id="config.public.GOOGLE_CLIENT_ID"
      data-context="signin"
      data-ux_mode="popup"
      data-callback="googleCallback" <!-- 去掉冒号,使用字符串 -->
      data-auto_prompt="false"
    ></div>
    
  • 改用手动初始化控制加载流程
    模板属性绑定可能因脚本加载时机问题导致异常,可在onMounted中动态加载脚本并手动初始化:

    import { onMounted } from 'vue';
    
    onMounted(() => {
      const script = document.createElement('script');
      script.src = 'https://accounts.google.com/gsi/client';
      script.async = true;
      script.defer = true;
      script.onload = () => {
        window.google.accounts.id.initialize({
          client_id: config.public.GOOGLE_CLIENT_ID,
          callback: googleCallback
        });
        window.google.accounts.id.renderButton(
          document.querySelector('.g_id_signin'),
          { 
            type: 'standard',
            shape: 'rectangular',
            theme: 'outline',
            text: 'signin_with',
            size: 'large',
            logo_alignment: 'left',
            width: '384'
          }
        );
      };
      document.body.appendChild(script);
    });
    

    这种方式能完全控制初始化流程,避免模板绑定的不确定性。

  • 检查客户端ID与授权域名配置
    确认nuxt.config.ts中public.GOOGLE_CLIENT_ID配置正确,且Google Cloud控制台中该OAuth客户端已添加当前项目的授权域名(比如本地开发的http://localhost:3000),域名不匹配会直接导致回调失效。

  • 清除浏览器缓存与登录状态
    浏览器缓存的旧Google登录会话可能干扰回调触发,清除相关缓存和Cookie后重新测试。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 11:57:42