Redirect VueJS:在两个页面之间重定向
我将Firebase与VueJS(和VueRouter)一起使用 我在重定向方面有问题。我想在两页之间重定向。第一个页面用于身份验证,第二个页面用于仅对登录用户可见的内容 Mystate持有firebase用户密钥(将通过调用firebase的变异来填充): 身份验证页面显示以下行:Redirect VueJS:在两个页面之间重定向,redirect,vue.js,Redirect,Vue.js,我将Firebase与VueJS(和VueRouter)一起使用 我在重定向方面有问题。我想在两页之间重定向。第一个页面用于身份验证,第二个页面用于仅对登录用户可见的内容 Mystate持有firebase用户密钥(将通过调用firebase的变异来填充): 身份验证页面显示以下行: beforeCreate() { if (this.$store.state.user.key !== null) { this.$router.replace('/') } } 以及秘密页面:
beforeCreate() {
if (this.$store.state.user.key !== null) {
this.$router.replace('/')
}
}
以及秘密页面:
beforeCreate() {
if (this.$store.state.user.key === null) {
this.$router.replace('/new')
}
}
但是:从身份验证页面到机密页面的重定向没有发生
我的Vue开发工具显示已设置用户密钥
这个问题的解决办法是什么
编辑:
这是调用Firebase并设置用户密钥的变体:
updateSession(state) {
auth.onAuthStateChanged((user) => {
if (user) {
state.user.key = user.uid
}
})
}
行动如下:
UPDATE_SESSION({ commit }) {
commit('updateSession')
}
我在我的根组件(App.vue)中调用该操作:
编辑2:
现在,我的路线阵列:
routes: [
{ path: '/', component: Secret },
{ path: '/new', component: Authentication }
]
查看文档中的“每路线警卫”部分: 你可能想试试下面的方法。通过在路线上设置进站前防护,您就是在告诉Vue先这样做。
next
参数告诉VueRouter下一步要做什么,并可以根据需要重定向或继续到原始路由
beforeEnter(to, from, next) {
if (this.$store.state.user.key === null) {
next('/new')
}
}
编辑
您可能还想尝试使用
推送
而不是替换
,根据我们在评论中的对话,您似乎需要:
store.dispatch
可以处理触发操作处理程序返回的承诺,它还返回承诺。看
因此,您可以设置登录操作以重签承诺,如下所示:
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
});
}
}
调用firebase api来设置用户密钥是一种异步调用,可能是身份验证页面中的
beforeCreate()
,在存储中设置用户密钥之前,会调用重定向到机密页面的beforeCreate()。那么,您可以显示变异代码吗?在该代码中,您可以通过调用Firebase设置用户密钥。您正在显示变异,但在App.vueSo中调度操作。您的机密组件是根url(“/”),是您的身份验证页a,登录页面,用户登录后,您想将其重定向到机密页面?您完全正确。是否可能,在beforeCreate
中,您的密钥为空,但稍后会更改?那么你应该试着用一个观察者。不,这不起作用。用户密钥已设置,重定向未发生。您可以发布JSFIDLE或codepen吗?我很乐意看一看。您可能还想尝试使用推送而不是替换。如果您直接导航到“秘密”路径,该路径是否有效?你能在定义路由的地方发布你的路由器路径对象吗?也许我可以使用类似用户密钥观察者的东西???@Timo你可以在这里了解承诺:并从我在回答中提供的链接中使用vuex操作中的承诺。我仍然没有真正理解承诺,你能提供一个js fiddle中的小示例吗?我会很感激的!!:D谢谢。@Timo,请看,数据是使用vue reource获取的,直到显示加载微调器,并且在获取完成后,将在promise中删除loding微调器
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
});
}
}