Vue.js 将错误传递给组件

Vue.js 将错误传递给组件,vue.js,Vue.js,我有一个AddComment.vue组件,它有一个表单,在提交时它会到达一个LaravelAPI端点,在那里进行验证。如果验证失败,我想在AddComment.vue中显示错误。如何将error.response对象返回到AddComment.vue?目前,当我想记录错误时,我可以在控制台中看到“fired”。我哪里出错了?如果您能提供帮助,我们将不胜感激 AddComponent.vue methods: { addComment() { this.$store.dis

我有一个
AddComment.vue
组件,它有一个表单,在提交时它会到达一个LaravelAPI端点,在那里进行验证。如果验证失败,我想在
AddComment.vue
中显示错误。如何将
error.response
对象返回到
AddComment.vue
?目前,当我想记录错误时,我可以在控制台中看到“fired”。我哪里出错了?如果您能提供帮助,我们将不胜感激

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)
            })
        });
    },
}
只有在Laravel后端抛出错误时,才会调用catch()块。因此,如果返回2xx的正常状态代码,那么axios总是调用.then()部分。在这种情况下,您必须自己解决错误消息

在后端路由中尝试类似的操作(它将返回错误):


并查看您的vuejs应用程序是否出现了实际错误。

感谢您抽出时间回复。如果我
console.log(error.response)
在addComment操作的捕获中得到了正确的json,那么端点工作正常。我认为问题在于如何将响应传递给
AddComment.vue
组件。啊,好吧,我认为这里缺少的是store.js中的返回表达式。将“返回新承诺…”添加到addComment函数的开头
return response()->toJson([
    'message' => 'error message',
], 500);