Vue中如何实现Google登录data-callback自定义HTML属性回调?
在Vue中实现Google身份认证回调的解决方案
问题背景
将Google身份认证的原生HTML代码迁移到Vue项目时,尝试用:data-callback绑定组件内的回调函数,发现控制台无输出,@data-callback也无效。原生可正常运行的HTML代码如下:
<div id="g_id_onload" data-client_id="YOUR_GOOGLE_CLIENT_ID" data-callback="handleCredentialResponse"> </div> <script> function handleCredentialResponse(response) { const responsePayload = decodeJwtResponse(response.credential); // 打印用户信息逻辑 } </script>
核心原因
Google身份认证脚本会从全局window作用域中查找data-callback指定的函数名称,但Vue组件内定义的函数属于模块作用域,不会自动暴露到全局,因此脚本无法找到并触发回调。
可行解决方案
方案1:将回调函数挂载到全局window
把组件内的回调函数挂载到window对象上,让Google脚本能找到它:
<script setup> import { onUnmounted } from 'vue' const handleCallback = (res) => { console.log({res}) // 这里添加JWT解码、用户信息处理逻辑 } // 挂载到全局作用域 window.handleCredentialResponse = handleCallback // 组件卸载时清理全局函数,避免内存泄漏 onUnmounted(() => { delete window.handleCredentialResponse }) </script> <template> <div id="g_id_onload" data-client_id="YOUR_GOOGLE_CLIENT_ID" data-callback="handleCredentialResponse"> </div> </template>
方案2:手动初始化Google Identity Services API(推荐)
这种方式更符合Vue组件化开发的规范,无需依赖全局函数:
<script setup> import { onMounted, onUnmounted } from 'vue' const handleCallback = (res) => { console.log({res}) // 自定义JWT解码函数 const decodeJwtResponse = (token) => { const base64Url = token.split('.')[1] const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/') const jsonPayload = decodeURIComponent( window.atob(base64).split('').map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2) ).join('') ) return JSON.parse(jsonPayload) } const userInfo = decodeJwtResponse(res.credential) console.log('用户信息:', userInfo) } onMounted(() => { // 动态加载Google GSI脚本 const script = document.createElement('script') script.src = 'https://accounts.google.com/gsi/client' script.onload = () => { // 初始化身份认证服务 window.google.accounts.id.initialize({ client_id: 'YOUR_GOOGLE_CLIENT_ID', callback: handleCallback }) // 渲染登录按钮(可自定义样式) window.google.accounts.id.renderButton( document.getElementById('google-login-btn'), { theme: 'outline', size: 'large' } ) } document.body.appendChild(script) }) onUnmounted(() => { // 组件卸载时清理资源 window.google?.accounts.id.disableAutoSelect() }) </script> <template> <div id="google-login-btn"></div> </template>
内容的提问来源于stack exchange,提问作者Roby Cigar
相关产品推荐
相关产品推荐

