首页 > 解决方案 > Vue 通知数组

问题描述

我在返回一系列通知时遇到了一些问题。我有一个运行良好的简单向导表单,如果可以,我将使用 Toastification 返回成功消息,如下所示:

this.$toast({
                            component: ToastificationContent,
                            props: {
                                title: 'Product Added',
                                icon: 'PlusIcon',
                                variant: 'success',
                            },
                        })

这很好用。但问题是列出一系列错误消息。我的后端返回如下错误:

{
    "response": false,
    "message": [
        "The sku has already been taken.",
        "The slug has already been taken."
    ]
}

所以我需要捕捉消息并向客户展示,所以我尝试了这样的事情:

.catch(error => {
                        console.log(error.response.data.message)

                        error.response.data.message.map(function(value, key) {
                             this.$toast({
                                component: ToastificationContent,
                                props: {
                                    title: 'Something bad happened',
                                    text: 'here must be a message from the array. How to catch it?',
                                    icon: 'XIcon',
                                    variant: 'danger',
                                },
                        })
                        });
                    });

但是每次我尝试使用它时,它都会说:

TypeError:无法读取未定义的属性“$toast”

任何想法如何解决这个问题?

标签: javascriptarraysvue.jsvuejs2

解决方案


在您的回调函数中,您会丢失 this 的上下文以获取其上下文,您可以使用箭头函数()=>

 error.response.data.message.map((value, key)=> {
   ...

代替

 error.response.data.message.map(function(value, key) {
  ...

推荐阅读