如何让Google Sign In调用Vue组件中的标准方法而非全局函数?
解决Vue组件中GSI回调无法调用组件方法的问题
方法一:临时挂载组件方法到全局(简易方案)
GSI的回调函数必须是全局作用域下的函数,Vue组件内部方法默认不在全局。可以在组件挂载时把方法挂到window上,销毁时移除避免全局污染:
<script setup lang="ts"> import { onMounted, onUnmounted } from 'vue' const handleSignIn = () => { console.log('signed in !') // 可直接调用组件内其他方法、访问响应式数据 } onMounted(() => { // 挂载到全局window对象 (window as any).handleSignIn = handleSignIn }) onUnmounted(() => { // 组件销毁时移除全局方法 delete (window as any).handleSignIn }) </script> <template> <div>Sign in</div> <div id="g_id_onload" data-client_id="43915.apps.googleusercontent.com" data-callback="handleSignIn" > </div> </template>
方法二:手动初始化GSI(更优雅的方案)
放弃g_id_onload自动初始化,改用GSI的JS API手动创建登录按钮,直接传入组件内部方法作为回调:
<script setup lang="ts"> import { onMounted } from 'vue' const handleSignIn = (response: any) => { console.log('signed in !', response) // 处理登录响应逻辑 } onMounted(() => { // 加载GSI脚本(未加载时才执行) if (!window.google) { const script = document.createElement('script') script.src = 'https://accounts.google.com/gsi/client' script.onload = initGoogleSignIn document.body.appendChild(script) } else { initGoogleSignIn() } function initGoogleSignIn() { // 手动初始化登录配置 window.google.accounts.id.initialize({ client_id: '43915.apps.googleusercontent.com', callback: handleSignIn // 直接传入组件方法 }) // 渲染登录按钮到指定容器 window.google.accounts.id.renderButton( document.getElementById('google-signin-button'), { theme: 'outline', size: 'large' } // 自定义按钮样式 ) } }) </script> <template> <div>Sign in</div> <!-- Google登录按钮渲染容器 --> <div id="google-signin-button"></div> </template>
为什么直接用:data-callback="handleSignIn"不行?
GSI自动初始化逻辑只会从全局window对象中,查找data-callback属性指定的字符串函数名。Vue的:data-callback是把组件方法作为值传递,但GSI不识别这种形式,因此会提示回调不是函数。
内容的提问来源于stack exchange,提问作者Richard
相关产品推荐
相关产品推荐

