我有使用 Alpine js 和 axios 為 POST 請求制作的模態表單組件。但我無法理解一些事情:
如何在成功的 POST 請求后重置表單資料。我在控制臺中看到錯誤
TypeError: this.resetFields is not a function如果 POST 請求由于 422 狀態碼的驗證錯誤而失敗,如何獲取錯誤以向用戶顯示。我想將 errors.message 系結到 AlpineJs 變數錯誤,然后使用 將其顯示在網頁上
<p x-text="errors" ></p>,但this.errors = error.message;似乎不起作用,因為在 Chrome 錯誤變數中的 AlpineJS devtools 中不會改變。
function modalform() {
return {
mailTooltip: false,
instagramTooltip: false,
openModal: false,
formData: {
name: '',
phone: '',
email: '',
address: '',
message: '',
_token: '{{ csrf_token() }}'
},
message: '',
errors: '',
loading: false,
sent: false,
buttonLabel: 'Send',
resetFields() {
this.formData.name = '',
this.formData.phone = '',
this.formData.email = '',
this.formData.address = '',
this.formData.message = ''
},
submitData() {
this.buttonLabel = 'Sending...';
this.loading = true;
this.message = '';
axios.post('/modalform', this.formData)
.then(function (response) {
console.log(response);
this.resetFields();
this.message = response.data.name;
})
.catch(function (error) {
console.log(error);
this.errors = error.message;
});
},
}
}
```
uj5u.com熱心網友回復:
你有一個范圍問題。如果您使用舊function(response){...}樣式,則this指的是呼叫它的物件 (axios)。但是,如果您將其替換為箭頭函式,this則將參考第一個非箭頭函式物件,在這種情況下:Alpine.js 組件。
axios.post('/modalform', this.formData)
.then((response) => {
console.log(response);
this.resetFields();
this.message = response.data.name;
})
.catch((error) => {
console.log(error);
this.errors = error.message;
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/460497.html
