将错误传递给组件

时间:2018-06-07 11:09:49

标签: vue.js

我有一个AddComment.vue组件,它有一个表单,在提交时会点击laravel api端点进行验证。如果验证失败,我想在AddComment.vue中显示错误。如何将error.response对象返回AddComment.vue?目前,我可以看到'解雇'在我想要记录错误的控制台中。哪里出错我会非常感谢任何帮助

AddComponent.vue

methods: {
    addComment() {
        this.$store.dispatch('addComment', {
            name: this.name,
            email: this.email,
            body: this.body
        })
        .then(response => {
            this.$router.push({ name: 'home' })
            console.log('fired')
        })
        .catch(error => {
            console.log(error)
        })
    },
}

store.js

actions: {
    addComment(context, comment) {
        new Promise((resolve, reject) => {
            axios.post('/comments', {
                name: comment.name,
                email: comment.email,
                body: comment.body,
                approved: false
            })
            .then(response => {
                context.commit('addComment', response.data)
                resolve(response)
            })
            .catch(error => {
                reject(error)
            })
        });
    },
}

1 个答案:

答案 0 :(得分:0)

只有在Laravel后端抛出错误时才会调用catch()块。因此,如果您返回正常状态代码2xx,则axios始终调用.then()部分。在这种情况下,您必须自己解决错误消息。

在后端路线中尝试这样的事情(它会返回错误):

return response()->toJson([
    'message' => 'error message',
], 500);

看看你的vuejs应用程序中是否存在实际错误。