svelte - 自定义 Google 登录按钮不会出现在 Svelte 中

标签 svelte google-signin

我正在尝试实现 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/

相关文章:

javascript - 是什么导致这个小型 Svelte 应用程序出现 "ctx[1] is not a function"错误?

Svelte:显示和隐藏复选框时分组复选框绑定(bind)问题

dart - 有没有人设法从谷歌登录 (Flutter) 获取 id token

ios - Google 登录与 Facebook 登录冲突

javascript - slim 的路线给了我 404

javascript - 在 Svelte 中, `:` 中的 `on:click` 是如何工作的?

Android Google Sign In 在用户登录时闪烁一个小的空白框

java - 尝试检索从 Google 登录下载的位图时出现 Skia 错误

iOS CocoaPod 警告 - "Google has been deprecated"- 使用 pod 'Google/SignIn' 时

javascript - 在 Svelte 中实现门户