I’m trying to implement a basic Google Login in Vue3 SFC, using the Google API. The Google login code is this HTML:
<component src="https://accounts.google.com/gsi/client" :is="'script'"></component>
<div id="g_id_onload"
data-client_id="454813487606-q3gep6aurieacd3kj02upb6fcfh2sqqb"
data-callback="handleCredentialResponse">
</div>
<div class="g_id_signin" data-type="standard"></div>
The value of the data-callback
attribute identifies the function to call after a successful Google login, in this case the function handleCredentialResponse
.
I’ve defined the callback function handleCredentialResponse
in the script setup code as follows:
<script setup lang="ts">
import { authStore } from '@/stores/authStore';
import { User } from '@/stores/authStore';
import { useRouter } from 'vue-router';
const router = useRouter();
const auth = authStore()
function handleCredentialResponse(googleUser: any) {
fetch('https://localhost:7237/myApi/ValidateToken?token=' + googleUser.credential, {
method: "GET",
})
.then(response => {
return response.json();
})
.then(data => {
auth.user = new User("Mr Test", data.token);
router.push(auth.returnUrl)
})
}
</script>
The callback function handleCredentialResponse
is never called. I can get the callback to work correctly if I define handleCredentialResponse
in the index.html file, but in that case I don’t have access to the store or router.
I’ve tried adding defineExpose({handleCredentialResponse})
but that didn’t work.
I assume I’m missing something very simple, I’m new to Vue3.