[英]How to use firebase auth in Vue
我的問題是,由於onAuthStateChanged在安裝componentm之后運行,因此路由器推送不起作用。
首先,我在vuex的store.js中進行了onAuthStateChanged。
// ./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
};
其次,當我在登錄組件處登錄時。 路由器中的signIn()推送效果很好。 之后,當我單擊登錄時,由於有關訪問的“ beforeCreate()”塊,它不允許我訪問“ /登錄”。
<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>
但是現在出現了問題。 當我使用重載直接在瀏覽器上訪問“ / signin” URL時,登錄組件的Create創建工作正常,然后onAuthStateChanged運行。 因此,登錄的this.router.push不起作用。 我怎么解決這個問題? 非常感謝您閱讀我的問題。
您可以在首次調用onAuthStateChanged
之后初始化vue應用。
// 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
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.