0
votes

I am working on a firebase based vue app that should redirect users to home page after successfully logged in. I receive howewer Cannot read property '$router' of undefined error in the console once clicked on login.

I already tried to import router from "./router" on Login component but it didn't work.

main.js

import Vue from "vue";
import firebase from "firebase";
import App from "./App.vue";
import router from "./router";
import swalPlugin from './plugins/VueSweetalert2';

Vue.config.productionTip = false;

let app ='';

firebase.initializeApp( {
apiKey: "xx",
authDomain: "xx",
databaseURL: "xx",
projectId: "xx",
storageBucket: "xx",
messagingSenderId: "xx"
});

Vue.use(swalPlugin);

firebase.auth().onAuthStateChanged(() => {
  if (!app) {
    app = new Vue({
      router,
      render: h => h(App)
    }).$mount("#app");
  }
});

router.js

import firebase from 'firebase';
import Vue from "vue";
import Router from "vue-router";
import Home from "./views/Home.vue";
import Login from "./views/Login.vue";
import SignUp from "./views/SignUp.vue";

Vue.use(Router);

const router = new Router({
  routes: [
    {
      path: "*",
      redirect: "/login",
    },
    {
      path: "/",
      redirect: "/login",
    },
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '/sign-up',
      name: 'SignUp',
      component: SignUp
    },
    {
      path: "/home",
      name: "Home",
      component: Home,
      meta: {
        requiresAuth: true
      }
    }
  ]
});

router.beforeEach ((to, from, next) => {
  const currentUser = firebase.auth.currentUser;
  const requiresAuth = to.matched.some (record => record.meta.requiresAuth);

  if (requiresAuth && !currentUser) next('login');
  else if (!requiresAuth && currentUser) next('home');
  else next();

});

export default router;

Login.vue

<template>
    <form autocomplete="off">
        <div class="login">
            <h1>Login</h1>
            <p>Sign in to stay updated with the latest news</p>
            <hr>

            <input type="text" placeholder="Email" v-model="email">

            <input type="password" placeholder="Enter Password" v-model="password">

            <hr>
            <button @click="login">Login</button>
            <p>Don't have an account yet? Create one <router-link to="/sign-up">here</router-link></p>

        </div>
    </form>
</template>


<script>
import firebase from 'firebase';
import Swal from 'sweetalert2';

export default {
    name: 'login',
    data() {
        return {
          email: '',
          password: ''
        }
    },
    methods: {
        login: function(){
            firebase.auth().signInWithEmailAndPassword(this.email, this.password).then(
              function (user) {
                this.$router.replace('home')
              },
              function (err) {
                Swal.fire({
                        type: 'error',
                        title: 'An error occurred...',
                        text: err.message
                })
              }
            );
        }
    }
}
</script>
1

1 Answers

4
votes

I think you lost your scope using function.

Solve it by using es6 syntax (if you can afford/using babel), (user) => { .. }.

Or by setting something like var _this = this; in the main login function and referencing that.