Vue.JS Firebase在成功身份验证时重定向



我有以下Vue.js应用程序结构(src目录(:

.
├── App.vue
├── assets
├── data
│   ├── config.js
├── main.js
├── router.js
└── views
└── app
├── index.vue
├── main
│   ├── dashboard.vue
│   └── index.vue
├── sessions
│   ├── index.vue
│   ├── login.vue

我已经实现了Firebase身份验证,它运行良好(参考data/config.js(。在我的login.vue中,我有登录表单和提交按钮:

<b-form @submit.prevent="formSubmit">
...
<b-button
type="submit"
...

它执行formSubmit方法:

<script>
...
methods: {
formSubmit() {
firebase
.auth()
.signInWithEmailAndPassword(this.email, this.password)
.then(data => {
this.$router.push('/app/main/dashboard').catch((err) => {
throw new Error(`${err}`);
});
})

.catch(err => {
console.log("not successful")
this.error = err.message;
alert(err.message);
});
},
},
...
</script>

如上所述,身份验证是有效的,我只是在成功通过身份验证后无法重定向到起始页。使用上面的代码,我得到

Uncaught (in promise) Error: undefined

在浏览器检查器中。我认为这与this语句有关,但我不知道如何重写它以获得成功的重定向。有人给我暗示吗?

谢谢!

我认为你应该这样做:

<script>
...
methods: {
firebase
.auth()
.signInWithEmailAndPassword(this.email, this.password)
.then(data => {
this.$router.push('/app/main/dashboard');
})
.catch(err => {
console.log("not successful")
this.error = err.message;
alert(err.message);
});
}
...
</script>

您不能在this.$router.push上调用catch。你也许可以把它包装在一个尝试和捕获块中:

try {
this.$router.push('/app/main/dashboard');
} catch (error) {
console.log(error) 
}

但我怀疑这是否有意义,因为无论是否可用,路线都会改变。我建议创建一个回退错误页面。就像这里提到的。

Vuex方法:

在存储文件夹中创建一个index.js文件。

import * as firebase from 'firebase'; 
export const state = () => ({})

export const actions = {
signInWithEmailAndPassword({ commit, dispatch }, payload) {
return firebase
.auth()
.signInWithEmailAndPassword(payload.email, payload.password)
.then(data => {
return Promise.resolve(data);
})
.catch(err => {
console.log("not successful")
this.error = err.message;
return Promise.reject(err);
});
}
}

然后在你的表单组件中:

<script>
...
methods: {
formSubmit() {
this.$store.dispatch("signInWithEmailAndPassword", { email: this.email, password: this.password } )
.then(data => {
this.$router.push('/app/main/dashboard');
});
}
}, ...
</script>

由于某些原因,我无法让它工作。我现在已经将signInWithEmailAndPassword放入store/index.js:中的export default new Vuex.Store

// Create store
export default new Vuex.Store({
modules: {
largeSidebar,
compactSidebar,
chat,
config,
authData,
invoice,
cart,
verticalSidebar,
scrumboard
},
actions: {
signInWithEmailAndPassword({ commit, dispatch }, payload) {
return firebase
.auth()
.signInWithEmailAndPassword(payload.email, payload.password)
.then(data => {
return Promise.resolve(data);
})
.catch(err => {
console.log("not successful")
this.error = err.message;
return Promise.reject(err);
});
}

}
});

但再次获得vue-router.esm.js?8c4f:2089 Uncaught (in promise) undefined

最新更新