[英]VueJS: Redirecting between two pages
我將Firebase與VueJS(和VueRouter)一起使用。
我在重定向時遇到問題。 我想在兩個頁面之間重定向。 第一頁用於身份驗證,第二頁用於僅對登錄用戶可見的內容。
我的州擁有firebase用戶密鑰(將通過一個名為firebase的突變填充):
state: {
user: { key: null }
}
身份驗證頁面的這些行:
beforeCreate() {
if (this.$store.state.user.key !== null) {
this.$router.replace('/')
}
}
和這些秘密頁面:
beforeCreate() {
if (this.$store.state.user.key === null) {
this.$router.replace('/new')
}
}
但是:從身份驗證頁面到機密頁面的重定向不會發生。
我的Vue-dev-tools顯示用戶密鑰已設置。
該問題的解決方案是什么?
編輯:
這是調用Firebase並設置用戶密鑰的突變:
updateSession(state) {
auth.onAuthStateChanged((user) => {
if (user) {
state.user.key = user.uid
}
})
}
這是動作:
UPDATE_SESSION({ commit }) {
commit('updateSession')
}
我在根組件(App.vue)中調用該動作:
beforeCreate() {
this.$store.dispatch('UPDATE_SESSION')
}
編輯2 :
現在我的路線數組:
routes: [
{ path: '/', component: Secret },
{ path: '/new', component: Authentication }
]
看看文檔的“按路線防護”部分: https : //router.vuejs.org/en/advanced/navigation-guards.html
您可能想要嘗試以下類似的方法。 通過在路線上放置beforeEnter保護,您可以告訴Vue首先這樣做。 next
參數告訴VueRouter下一步做什么,可以根據需要重定向或繼續到原始路由。
beforeEnter(to, from, next) {
if (this.$store.state.user.key === null) {
next('/new')
}
}
編輯
您可能還想嘗試使用push
而不是replace
根據我們在評論中的對話,您看起來像這樣:
store.dispatch
可以處理由觸發的操作處理程序返回的Promise,並且還返回Promise。 參見docs 。
因此,您可以設置登錄操作以取消如下所示的承諾:
a_logInUser: ({state, commit}, userInput) => {
return new Promise((resolve, reject) => {
firebase.auth().signInWithEmailAndPassword(userInput.email, userInput.paswword);
resolve();
});
}
然后,在您的身份驗證頁面中,您對登錄輸入的詳細信息進行描述並單擊登錄按鈕,將其設置為登錄按鈕的單擊處理程序。
loginUser(){
this.$store.dispatch('a_logInUser', {email: this.email, password: this.password})
.then((result) => {
this.$router.replace('/');
}, (err) => {
// stay on this pageS
//handle login error
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.