Render变量显示[对象对象],而不是其值



使用AlpineJS,当API返回错误时,我正在提交表单并显示错误消息:

<form x-data="inquiry()" x-on:submit.prevent="submit" method="post">
<label>Name</label>
<input type="text" name="name" x-model="data.name.value">
<span x-show="data.name.error !== null" x-text="data.name.error"></span>
<label>Email</label>
<input type="text" name="email" x-model="data.email.value">
<span x-show="data.email.error !== null" x-text="data.email.error"></span>
<button>Submit</button>
</form>
<script type="text/javascript">
function inquiry() {
return {
data: {
name: { value: "", error: null },
email: { value: "", error: null }
},
submit() {
fetch("/inquiries", {
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
name: this.data.name.value,
email: this.data.email.value
})
.then((response) => {
if (response.ok) {
} else {
response.json().then((body) => {
for (const key in this.data) 
this.data[key].error = body.errors.find(x => x.source.toLowerCase() == key.toLowerCase()) ?? null;
});
}
})
}
};
}
</script>

当我提交有错误的表格时,我得到的回复是:

{
"errors": [
{ "source": "Email", "detail": "The email is invalid" },
{ "source": "Name", "detail": "The name is required" },
]
}

但是,例如,将显示name的错误详细信息的span呈现:

[object Object]

我错过了什么?

可能是这样的:

var resp = {
"errors": [
{ "source": "Email", "detail": "The email is invalid" },
{ "source": "Name", "detail": "The name is required" }
]
};
if(resp['errors']){ //if error exist in response
alert('ERRORS: nn' + JSON.stringify(resp['errors'], null, 4));
}

您将data[key].error的值设置为从主体中找到的对象行,而不是设置为对象内部的错误

这将修复它:

for (const key in data) {
this.data[key].error = body.errors.find(x => x.source.toLowerCase() == key.toLowerCase())?.detail ?? null;
}

我使用?.(可选chainig(作为对象行可能不存在,但如果存在,我们将从该行获取detail值。如果它是undefined,或者detail不存在,它将默认为null