简体   繁体   中英

How to use firebase auth in Vue

My problem is that since the onAuthStateChanged runs after mounting componentm, the router push doesn't work.

First, I made onAuthStateChanged at store.js of vuex.

// ./src/vuex/store.js

import { firebaseAuth } from "../firebase/firebaseAuth";

Vue.use(Vuex);

firebaseAuth.onAuthStateChanged(user => {
  if (user) {
    console.log(user);
    state.user = user;
  } else {
    state.user = null;
  }
});

const state = {
  user: null
};


Second, when I sign in at the sign in component. The router push in the signIn() works well. And after that, when I click signin, it doesn't allow me to access '/signin' due to that 'beforeCreate()' block about acessing.

<script>
import { firebaseAuth } from "../firebase/firebaseAuth";
import { mapGetters } from "vuex";

export default {
  name: "sighin",
  beforeCreate() {
    console.log(this.$store.state.user);
    if (this.$store.state.user) {
      this.$router.push("/");
    }
  },
  data() {
    return {
      email: "",
      password: ""
    };
  },
  computed: {
    ...mapGetters({ user: "getUser" })
  },
  methods: {
    signIn() {
      firebaseAuth.signInWithEmailAndPassword(this.email, this.password).then(
        user => {
          this.$router.push("/");
        },
        err => {
          alert("Oops. " + err.message);
        }
      );
    }
  }
};
</script>

But the problem occurs now. When I access '/signin' url directly at the browser using reload, beforeCreate of signin Component works, after that, onAuthStateChanged runs. Thus, this.router.push of signin doesn't work. How can I solve this problem? THank you so much for reading my question.

You can init vue app just after onAuthStateChanged first call.

    // main.js
    const unsubscribe = firebaseAuth.onAuthStateChanged(user => {
            new Vue({
                el: '#app',
                router,
                store,
                render: h => h(App)
            })
            unsubscribe() // unsubscribe to call init function only once
        }
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM