我正在尝试实现 Google 指南上的自定义 Google 登录按钮示例,但它甚至没有调用回调。如果我使用纯 HTML 和 Javascript,它可以工作,但不能在 Svelte 中:
自定义GoogleSignInButton.svelte
<script>
function onSuccess(googleUser) {
console.log("Logged in as: " + googleUser.getBasicProfile().getName());
}
function onFailure(error) {
console.log(error);
}
function renderButton() {
gapi.signin2.render("my-signin2", {
scope: "profile email",
width: 240,
height: 50,
longtitle: true,
theme: "dark",
onsuccess: onSuccess,
onfailure: onFailure
});
}
</script>
<svelte:head>
<script
src="https://apis.google.com/js/platform.js?onload=renderButton"
async
defer>
</script>
</svelte:head>
<div id="my-signin2" />
我在 head 标签中也有元。
最佳答案
onload=renderButton
表示“加载此脚本时,调用名为 renderButton
的全局函数” 。 <script>
中声明的函数 block 对于组件来说是本地,因此没有全局 renderButton
.
您可以通过将函数添加到窗口对象来解决它...
window.renderButton = function() {
gapi.signin2.render("my-signin2", {
scope: "profile email",
width: 240,
height: 50,
longtitle: true,
theme: "dark",
onsuccess: onSuccess,
onfailure: onFailure
});
}
...但您也可以使用本地函数,如下所示:
<svelte:head>
<script
src="https://apis.google.com/js/platform.js"
on:load={renderButton}
async
defer>
</script>
</svelte:head>
如果有效,最好不要污染 window
对象。
关于svelte - 自定义 Google 登录按钮不会出现在 Svelte 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64737548/