使用Google Auth Signin的Vuejs全球功能

raf*_*fff 9 javascript google-authentication vue.js vuejs2

我正在使用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');
          });
      }
  },
};
Run Code Online (Sandbox Code Playgroud)

我的主要问题是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>
Run Code Online (Sandbox Code Playgroud)

这按预期工作,但我想知道是否可以在我的vue文件而不是本机javascript方式中添加它,因为在此函数内部,我将调用其他vue方法.

或者有没有办法我可以onSignIn(googleUser)在vue中添加该功能,然后在Google Auth完成时调用它?

Phi*_*hil 11

这里的解决方案是用于gapi.signin2.render在组件的mounted钩子内渲染登录按钮

<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>
Run Code Online (Sandbox Code Playgroud)

请参阅https://developers.google.com/identity/sign-in/web/reference#gapisignin2renderid-options