I've been attempting to access the global object Vue.prototype.$firebase
, which is declared in main.js
.
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import VueTailwind from "vue-tailwind";
import { FirebaseApp } from "@/firebase/firebase";
//Style
import "@/assets/styles/app.css";
import settings from "@/assets/styles/Tailwind.js";
FirebaseApp.auth().onAuthStateChanged((user)=>{
Vue.prototype.$user = user;
})
//Vue
Vue.config.productionTip = false;
Vue.use(VueTailwind, settings);
Vue.prototype.$firebase = FirebaseApp;
new Vue({
router,
render: h => h(App)
}).$mount("#app");
within a Login
component:
<script>
export default {
name: "Login",
mounted: function () {
this.submit();
},
methods: {
submit() {
let login = document.getElementById("login");
login.addEventListener(
"submit",
function (event) {
event.preventDefault();
const email = login.email.value;
const password = login.password.value;
this.$firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then((user) => {
console.log(user)
this.$router.replace('/')
})
.catch((error) => {
console.log(error);
});
},
true
);
},
},
};
</script>
However, I encountered a
TypeError: Cannot read property 'auth' of undefined
, along with issues accessing this.$router
. Moving the object instantiation outside of the .addEventListener
provided access through let signIn
, but that's not the desired behavior. Instead, I want to automatically route between login
and dashboard
on onAuthStateChange
by using Vue.prototype.$firebase
instead of local instantiation.
<script>
export default {
name: "Login",
mounted: function () {
this.submit();
},
methods: {
submit() {
let login = document.getElementById("login");
let signIn = this.$FirebaseApp;
let onLogin = this.$router;
login.addEventListener(
"submit",
function (event) {
event.preventDefault();
const email = login.email.value;
const password = login.password.value;
signIn
.auth()
.signInWithEmailAndPassword(email, password)
.then((user) => {
console.log(user)
onLogin.replace('/')
})
.catch((error) => {
console.log(error);
});
},
true
);
},
},
};
</script>
What is the correct way to access Vue.prototype.$firebase
and why does it have such scope limitations?