Javascript 带有Google Auth Signin的Vuejs全局函数

Javascript 带有Google Auth Signin的Vuejs全局函数,javascript,vue.js,vuejs2,google-authentication,Javascript,Vue.js,Vuejs2,Google Authentication,我正在使用vuejs 2,我在使用Google auth signin时遇到问题 我使用vue成功设置并使注销和用户配置文件功能正常工作: export default { data() { return { user: null }; }, methods: { getUserProfile() { const profile = gapi.auth2.currentUser.get().getBasicProfile()

我正在使用vuejs 2,我在使用Google auth signin时遇到问题

我使用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)
函数

data onsuccess=“onSignIn”
正在vue实例之外寻找js函数。 我尝试在HTML文件中添加
onSignIn(googleUser)
函数,如下所示:

<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>

函数onSignIn(谷歌用户){
const auth2=gapi.auth2.init();
if(auth2.isSignedIn.get()){
const profile=auth2.currentUser.get().getBasicProfile();
console.log(profile.getName());
log(googleUser.getAuthResponse().id_令牌);
log(googleUser.getAuthResponse().uid);
log(auth2.currentUser.get().getId());
}
}
这正如预期的那样工作,但我想知道是否有可能在我的vue文件中添加它,而不是以本机javascript的方式,因为在这个函数中,我将调用其他vue方法


或者有没有一种方法可以让我在vue中添加
onSignIn(googleUser)
函数,然后在GoogleAuth完成时调用它

这里的解决方案是使用
gapi.signn2.render
在组件的
挂载的
钩子中呈现登录按钮

<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>

导出默认值{
方法:{
onSignIn(用户){
//例如,做一些事情
const profile=user.getBasicProfile()
}
},
安装的(){
gapi.signn2.render('google-signin-btn',{//这是按钮“id”
onsuccess:this.onSignIn//注意,此处没有“()”
})
}
}

请参见

这项功能可以正常工作,但在尝试访问获取当前用户详细信息所需的
gapi.auth2.init()
时,
onSignIn
函数总是失败。我假设
mounted
在google auth仍在运行时调用
onSignIn
,这就是
gapi.auth2.init()
失败的原因。如何防止这种情况发生?@raffffffff不太可能,
onSignIn
只有在按钮完成登录过程后才会被调用。你能更好地定义这个问题吗?如果您刚刚了解了用户详细信息,则可以从传递到
onSignIn
user
获取这些信息。我将添加一个例子,你们是如何使gapi在全球范围内可用的@Phil@CamHart在你的
index.html
中包含来自谷歌的脚本,你是如何让gapi在全球范围内可用的?@CamHart我跟随了这篇文章