Authentication
Once you have installed the plugin, here is a conventional Vue.js v3.x component that displays a login or logout button based on a detected authenticated state.
Component
import { computed, ref } from 'vue'
import { useGapi } from 'vue-gapi'
export default {
setup() {
const gapi = useGapi()
// (1) Subscribe to authentication status changes
const isSignedIn = ref(null)
gapi.listenUserSignIn((value) => {
isSignedIn.value = value
})
// (2) Display authenticated user name
const userName = computed(() => {
const user = gapi.getUserData()
return user ? user.firstName : undefined
})
// (3) Expose $gapi methods
function login() {
gapi.login().then(({ currentUser, gapi, hasGrantedScopes }) => {
console.log({ currentUser, gapi, hasGrantedScopes })
})
}
function logout() {
gapi.logout()
}
return {
isSignedIn,
userName,
login,
logout,
}
},
template: '#login-template',
}
Template
<script type="text/x-template" id="login-template">
<div>
<div v-if="isSignedIn">
<button @click="logout()" type="button">Logout</button>
{{ userName }}
</div>
<button
:disabled="isSignedIn === null"
@click="login()"
type="button"
v-if="!isSignedIn"
>
Login
</button>
</div>
</script>
Subscribe to authentication status changes via
listenUserSignIn
.Expose
login
andlogout
methods.Most
$gapi
methods return a promise. See theGoogleAuthService
reference documentation for more details.Display the authenticated user's name via
getUserData
.See the
UserData
reference documentation for a full list of user object properties which are persisted in local storage in practice.