首页 > 解决方案 > 如何正确地将谷歌登录代码放入 nuxt 组件中

问题描述

谷歌在https://developers.google.com/identity/sign-in/web中提供了一个友好的 .html 代码 我在一个 .html 文件中尝试了这个代码,它工作得很好。用户登录后,每次加载页面时都会撤销onSignin,这意味着将在控制台中登录用户信息但是如果我在nuxt组件中使用此代码,则只会运行登录过程,onSignIn函数没有被撤销,也没有显示错误。这是我的代码:

<template>
  <div class="g-signin2" data-onsuccess="onSignIn"></div>
</template>
<script>
/* eslint-disable */
function onSignIn(googleUser) {
  // Useful data for your client-side scripts:
  var profile = googleUser.getBasicProfile()
  console.log('ID: ' + profile.getId()) // Don't send this directly to your server!
  console.log('Full Name: ' + profile.getName())
  console.log('Given Name: ' + profile.getGivenName())
  console.log('Family Name: ' + profile.getFamilyName())
  console.log('Image URL: ' + profile.getImageUrl())
  console.log('Email: ' + profile.getEmail())

  // The ID token you need to pass to your backend:
  var id_token = googleUser.getAuthResponse().id_token
  console.log('ID Token: ' + id_token)
}
export default {
  head() {
    return {
      meta: [
        {
          name: 'google-signin-scope',
          content: 'profile email'
        },
        {
          name: 'google-signin-client_id',
          content: process.env.GOOGLE_CLIENT_ID
        }
      ],
      script: [
        {
          src: 'https://apis.google.com/js/platform.js',
          defer: true,
          async: true
        }
      ]
    }
  }
}
</script>

我确定 process.env.GOOGLE_CLIENT_ID 是正确的,因为我在浏览器上运行时检查了 dom 树。如果知道bug出在哪里,请告诉我,谢谢。

标签: google-oauthnuxt.js

解决方案


Vue SFC 的脚本是隔离的,你刚刚声明onSignIn的就在这个范围内。是的,这不会飞。

幸运的是,您可以简单地onSignIn在范围内添加函数window

window.onSignIn = onSignIn

大多数情况下,你已经做好了。但甚至还有专门为这个用例准备的包:google-signin-vue。我不建议盲目使用它;相反,如果需要,请查看源代码并找到您想要的功能。


推荐阅读