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

Vue3+Vue Router环境下Google OAuth登录按钮无法渲染问题

解决Vue Router中Google OAuth登录按钮不渲染的问题

核心原因

Google GSI脚本默认在页面首次加载时扫描DOM生成登录按钮,但Vue Router切换视图时,SignUpView的DOM是后续动态挂载的,此时GSI已经完成了初始扫描,不会自动识别新的按钮元素,导致按钮无法稳定渲染。

解决方案

在SignUpView组件中,手动触发GSI的按钮初始化逻辑,确保组件挂载后重新生成按钮:

  1. 模板中保留按钮容器
    给按钮容器设置明确的选择器,方便后续定位:
<template>
  <div class="signup-container">
    <!-- Google登录按钮容器 -->
    <div class="g_id_signin"></div>
  </div>
</template>
  1. 组件挂载时手动初始化按钮
    使用Vue3组合式API的onMounted钩子,调用GSI的官方方法手动渲染按钮:
<script setup>
import { onMounted } from 'vue'

onMounted(() => {
  // 确保GSI脚本已加载完成
  const initGoogleSignIn = () => {
    if (!window.google?.accounts?.id) return
    
    google.accounts.id.renderButton(
      document.querySelector('.g_id_signin'),
      {
        client_id: '你的CLIENT_ID',
        login_uri: '你的回调URI',
        type: 'standard',
        size: 'large',
        theme: 'outline',
        text: 'sign_in_with',
        shape: 'rectangular',
        logo_alignment: 'left'
      }
    )
  }

  // 若脚本已加载直接初始化,否则等页面加载完成后再执行
  if (document.readyState === 'complete') {
    initGoogleSignIn()
  } else {
    window.addEventListener('load', initGoogleSignIn)
  }
})
</script>
  1. 可选:路由切换时清理按钮实例
    避免重复创建按钮实例,在组件卸载时销毁已生成的按钮:
<script setup>
import { onMounted, onUnmounted } from 'vue'

let signInButtonInstance = null

onMounted(() => {
  const initGoogleSignIn = () => {
    if (!window.google?.accounts?.id) return
    
    signInButtonInstance = google.accounts.id.renderButton(
      document.querySelector('.g_id_signin'),
      // 配置项同上
    )
  }

  // 初始化逻辑同上
})

onUnmounted(() => {
  if (signInButtonInstance && window.google?.accounts?.id) {
    google.accounts.id.cancel(signInButtonInstance)
  }
})
</script>

额外注意事项

  • 不要在index.html的GSI脚本标签上添加async或defer,若必须添加,需确保脚本加载完成后再执行初始化(上述代码已兼容这种情况)
  • 避免同时在模板中写data-client_id等属性和手动传入配置,防止冲突
  • 测试前清除浏览器缓存,确保GSI脚本为最新版本

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 14:15:06