I'm fairly new to Vue and this is the second tutorial I'm following, which integrates firebase backend with Vue. But the tutorial is using Vue 2 and also an older version of firebase, so I thought I could try to do it with Vue 3 and the new Firebase version.
The resources on the firebase 9.0.1 seems to be fairly limited with regards to implementation with Vue at least. This is what I found from the firebase documentation regarding the signInAnonymously
import { getAuth, signInAnonymously } from "firebase/auth";
const auth = getAuth();
signInAnonymously(auth)
.then(() => {
// Signed in..
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ...
});
From what I understand, firebase 9.0.1 is an import only what you use style? so If I want to use the getAuth and signInAnonymously methods from the firebase/auth, I would do
import { getAuth, signInAnonymously } from 'firebase/auth';
But I am a bit confused as to how to use the methods in my .Vue file so what I did in my firebase.js file was
export const auth = getAuth();
export {signInAnonymously};
then in my Login.vue file, i did
import { auth, signInAnonymously } from '../firebase'
export default {
data() {
return { auth }
},
methods: {
signInAnonymously
}
}
and I have a button that when clicked triggers the signInAnonymously, which is written like so
<button class="button" @click="signInAnonymously(auth)">Sign In</button>
What I have written seems to work, but I find it a bit convoluted/confusing and want to know
signInAnonymously method as shown in the firebase documentation, i.e. adding those signInAnonymously(auth).then(() => {}), because if i were to add the arguments for the signInAnonymously in my export default like below, it doesn't recognize it as the exported method from my firebase.js file?
export default {
...,
methods: {
signInAnonymously(auth) {
...
}
}
Try creating a custom method and using signInAnonymously() within that as shown below:
import { auth } from '../firebase'
import { signInAnonymously } from 'firebase/auth'
// can be imported directly in Login.vue ^^
export default {
methods: {
anonymousLogin() {
// Directly pass 'auth' in this method
signInAnonymously(auth)
.then(() => {
// Signed in..
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ...
});
},
},
};
Then use this custom method in @click event:
<button class="button" type="button" @click="anonymousLogin">Sign In</button>