The QForm component renders a <form>
DOM element and allows you to easily validate child form components (like QInput, QSelect or your QField wrapped components) that have the internal validation (NOT the external one) through rules
associated with them.
用法
警告
請注意以下事項
- QForm 鉤入 QInput、QSelect 或 QField 包裝的元件
- QInput、QSelect 或 QField 包裝的元件必須使用內部驗證 (而非外部驗證)。
- 如果您想要利用
reset
功能,請務必也捕捉 QForm 上的@reset
事件,並使其處理常式重置所有包裝元件的模型。
為了讓使用者能夠啟用表單上的 @submit
或 @reset
事件,請建立一個 type
設定為 submit
或 reset
的 QBtn。
<div>
<q-btn label="Submit" type="submit" color="primary"/>
<q-btn label="Reset" type="reset" color="primary" flat class="q-ml-sm" />
</div>
content_paste
或者,您可以給 QForm 一個 Vue ref 名稱,並直接呼叫 validate
和 resetValidation
函數。
// <q-form ref="myForm">
setup () {
const myForm = ref(null)
function validate () {
myForm.value.validate().then(success => {
if (success) {
// yay, models are correct
}
else {
// oh no, user has filled in
// at least one invalid value
}
})
}
// to reset validations:
function reset () {
myForm.value.resetValidation()
}
return {
myForm,
// ...
}
}
content_paste
關閉自動完成
如果您想要關閉某些瀏覽器對表單中所有輸入元素使用自動校正或拼字檢查的方式,您也可以將這些純 HTML 屬性新增到 QForm 元件。
autocorrect="off"
autocapitalize="off"
autocomplete="off"
spellcheck="false"
content_paste
提交到 URL (原生表單提交)
如果您在 QForm 上使用原生 action
和 method
屬性,請記得在每個 Quasar 表單元件上使用 name
prop,以便傳送的 formData 實際包含使用者填寫的內容。
<q-form action="https://some-url.com" method="post">
<q-input name="firstname" ...>
<!-- ... -->
</q-form>
content_paste
- 透過設定 QForm 的
action
、method
、enctype
和target
屬性來控制表單提交的方式。 - 如果 QForm 上**沒有**
@submit
的監聽器,則驗證成功後將提交表單。 - 如果 QForm 上**有**
@submit
的監聽器,則驗證成功後將呼叫該監聽器。 在這種情況下要執行原生提交
<q-form action="https://some-url.com" method="post" @submit.prevent="onSubmit">
<q-input name="firstname" ...>
<!-- ... -->
</q-form>
content_paste
methods: {
onSubmit (evt) {
console.log('@submit - do something here', evt)
evt.target.submit()
}
}
content_paste
子元件溝通
預設情況下,所有 Quasar 表單元件都會與父 QForm 實例通訊。 如果由於某些原因,您正在建立自己的表單元件 (**不包裝 Quasar 表單元件**),則可以使用以下方式讓 QForm 感知到它:
import { useFormChild } from 'quasar'
setup () {
// function validate () { ... }
useFormChild({
validate, // Function; Can be async;
// Should return a Boolean (or a Promise resolving to a Boolean)
resetValidation, // Optional function which resets validation
requiresQForm: true // should it error out if no parent QForm is found?
})
}
content_paste