I am using vuejs 2 and I am having issues with using the Google auth signin.
I successfully setup and got the sign out and user profile functions working using 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');
});
}
},
};
My main issue here is the onSignIn(googleUser)
function from
<div class="g-signin2" data-onsuccess="onSignIn"></div>
The data-onsuccess="onSignIn"
is looking for a js function outside the vue instance.
I tried adding the onSignIn(googleUser)
function in my HTML file like:
<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>
This works as expected, but I wanted to know if it would be possible to add this in my vue file instead of a native javascript way, since inside this function, I will be calling other vue methods.
Or is there a way where I could add the onSignIn(googleUser)
function in vue and then call it when Google Auth finishes?
The solution here is to use gapi.signin2.render
to render the sign-in button inside your component's 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>
See https://developers.google.com/identity/sign-in/web/reference#gapisignin2renderid_options