温州旅游 网站建设深圳网站设计网站建设哪个好
目录
前置操作
具体步骤
加载js文件
初始化google登录对象
生成登录按钮
一键式登录功能
相关文档
海外项目避免不了接入谷歌登录,下面记录一下我的实现步骤吧!(vue3项目)
前置操作
首先要经过谷歌OAuth2.0来验证和授权,配置网站域名以及生成客户端ID
创建账号网址
参考网上的一篇博客:大佬的博客
具体步骤
加载js文件
在index.html引入Google API的js地址
<script src="https://accounts.google.com/gsi/client" async defer></script>
初始化google登录对象
可以在App.vue中初始化google登录,初始化后,登录对象全局生效,后续其他页面调用API不用再初始化了
- google.accounts.id.initialize 方法需要在onload 回调函数中调用
- callback 参数是登录成功的回调函数,可获取的参数包括客户端ID、用户的ID令牌等。业务中可以拿这些参数与后端交互,获取本项目中可使用的用户信息。
window.onload = () => {initGoogle()
}// 初始化google - 全局生效
function initGoogle() {try {google.accounts.id.initialize({client_id: "前置步骤配置生成的客户端ID",callback: handleCredentialResponse,use_fedcm_for_prompt: true});} catch (error) {console.log('app google error1', error.message);// Toast(`Google Api初始化失败, 请稍后再试`)}
}
生成登录按钮
UI图设计的是这种
因为UI图设计的具有不确定性,所以我们要写一个登录按钮放在原生按钮的下面,把原生按钮的透明度设置为0.01(本来要设置为0,发现点击不能登录了)
// template
<div class="login_button"><img src="@/assets/img/google-icon.png" alt=""><div class="text">Sign in with Google</div><div id="googleSignInButton"> </div>
</div>// JS
function showDialog() {show.value = truecreateLoginButton()
}function createLoginButton() {try {google.accounts.id.renderButton(document.getElementById("googleSignInButton"),{ type: 'standard', theme: "outline", shape: 'circle', size: "large", width: 320, text: '使用 Google 账号登录' } // 你可以自定义按钮的主题和大小);} catch (error) {console.log('login google error2', error.message);}
}// css
.login_button {width: 320px;height: 48px;margin: 39px auto 62px auto;background: #185ABC;border-radius: 50px;padding: 0 34px;display: flex;align-items: center;cursor: pointer;position: relative;img {width: 24px;margin-right: 31px;flex-shrink: 0;}.text {font-weight: 500;font-size: 16px;color: #FFFFFF;line-height: 22px;}#googleSignInButton {position: absolute;top: 4px;left: 1px;z-index: 10;opacity: 0.01;}
}
调整透明度,可以看到原生按钮
点击后,会弹出一个浏览器弹框,选择账号即可登录了
一键式登录功能
网站右上角自动弹出登录弹框
// 弹出登录提示
function createLoginPrompt() {try {google.accounts.id.prompt((notification) => {});} catch (error) {console.log('google error', error.message);}
}
相关文档
最新文档,登录注意事项
JS API文档