google-oauth - 如何正确地将谷歌登录代码放入 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出在哪里,请告诉我,谢谢。
解决方案
Vue SFC 的脚本是隔离的,你刚刚声明onSignIn
的就在这个范围内。是的,这不会飞。
幸运的是,您可以简单地onSignIn
在范围内添加函数window
:
window.onSignIn = onSignIn
大多数情况下,你已经做好了。但甚至还有专门为这个用例准备的包:google-signin-vue。我不建议盲目使用它;相反,如果需要,请查看源代码并找到您想要的功能。
推荐阅读
- angular - 角度可观察的未定义值
- java - 我只是在使用 kotlin 中的高阶函数。我正在传递这两个字符串参数
- javascript - 如何解决$不是函数
- javascript - 在 state 中使用方法 args 做出反应
- amazon-cognito - AWS Cognito 如何在多个 UserPools 中对用户进行身份验证
- php - php文件在服务器上有效,但在部署时无效
- wordpress - 为什么主题我不想翻译这个词
- jquery - 如何使用 V8ScriptEngine (Clearscript) 在 c# 代码中加载 jquery 文件?
- node.js - 如何处理 HTTP 请求对 Node.js 性能的影响
- stored-procedures - 如何在 where 子句中使用存储函数(过程)?(Entity Framework Core 2.0)