javascript - 带有 Google Auth Signin 的 Vuejs 全局函数

标签 javascript vue.js vuejs2 google-authentication

我正在使用 vuejs 2,但在使用 Google 身份验证登录时遇到问题。

我使用 vue 成功设置并获得了注销和用户配置文件功能:

export default {

  data() {
    return {
      user: null
    };
  },

  methods: {
    getUserProfile() {
          const profile = gapi.auth2.currentUser.get().getBasicProfile();

          console.log(profile.getIdToken());
      },

      signOut() {
          const auth2 = gapi.auth2.getAuthInstance();

          auth2.signOut().then(function () {
              console.log('user signed out');
          });
      }
  },
};

我这里的主要问题是 onSignIn(googleUser)功能来自

<div class="g-signin2" data-onsuccess="onSignIn"></div>

data-onsuccess="onSignIn"正在vue实例之外寻找一个js函数。 我尝试添加 onSignIn(googleUser)在我的 HTML 文件中的功能如下:

<script>
    function onSignIn(googleUser) {
        const auth2 = gapi.auth2.init();

        if (auth2.isSignedIn.get()) {
            const profile = auth2.currentUser.get().getBasicProfile();

            console.log(profile.getName());
            console.log(googleUser.getAuthResponse().id_token);
            console.log(googleUser.getAuthResponse().uid);
            console.log(auth2.currentUser.get().getId());
        }
    }
</script>

这按预期工作,但我想知道是否可以将它添加到我的 vue 文件中而不是原生 javascript 方式,因为在这个函数中,我将调用其他 vue 方法。

或者有什么方法可以添加 onSignIn(googleUser)在 vue 中运行然后在 Google Auth 完成时调用它?

最佳答案

这里的解决方案是使用 gapi.signin2.render 在组件的 mounted Hook 中呈现登录按钮

<template>
  <div id="google-signin-btn"></div>
</template>

<script>
export default {
  methods: {
    onSignIn (user) {
      // do stuff, for example
      const profile = user.getBasicProfile()
    }
  },
  mounted() {
    gapi.signin2.render('google-signin-btn', { // this is the button "id"
      onsuccess: this.onSignIn // note, no "()" here
    })
  }
}
</script>

参见 https://developers.google.com/identity/sign-in/web/reference#gapisignin2renderid_options

关于javascript - 带有 Google Auth Signin 的 Vuejs 全局函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43130296/

相关文章:

javascript - 如何创建点击事件以在不同的 HTML 页面上打开特定的 Bootstrap 选项卡?

javascript - 在 Vue.js 中绑定(bind)多个数字文本框

apache - 为 VUE-JS SPA 设置 .htaccess 重写规则

vue.js - 如何将带有 Jest 的 Vue Test Utils 添加到现有的 Vue-CLI 3 项目中?

javascript - Vue.js 缓存方法结果?

javascript - 验证用户是否已登录的正确方法

javascript - 如何将 Backbone 函数作为参数传递

javascript - 路由内容未在 Vue-router 和 Laravel 中显示

vue.js - Vite构建模式开发结果报错Could notresolveent module "development/index.html"

javascript - angularjs - 如果我的响应在运行时改变结构,如何生成动态页面