Form जमा करना
Vue में एक form का submit event handle करें और browser को page reload करने से रोकें।
In this page:
Syntax
<form @submit.prevent="submitHandler">
<input v-model="field">
<button type="submit">Send</button>
</form>
Form Submission
@submit.prevent से सुनें ताकि default page reload cancel हो जाए, फिर bound data पढ़ें और इसे भेजें, उदाहरण के लिए fetch से। feedback देने के लिए data में loading और error states track करें। एक successful submission के बाद fields reset करें।
Note:
button पर @click की बजाय form पर @submit.prevent इस्तेमाल करें, ताकि Enter दबाना भी काम करे।
उदाहरण: Form submission
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<form @submit.prevent="submit">
<input v-model="name" required>
<button :disabled="sending">{{ sending ? "Sending..." : "Send" }}</button>
</form>
<p>{{ result }}</p>
</div>
<script>
Vue.createApp({
data() { return { name: "Ada", sending: false, result: "" }; },
methods: {
async submit() {
this.sending = true;
await new Promise((r) => setTimeout(r, 10)); // pretend network call
this.result = "Saved " + this.name;
this.sending = false;
},
},
}).mount("#app");
document.querySelector("form").dispatchEvent(new window.Event("submit", { cancelable: true }));
setTimeout(() => console.log(document.querySelector("p").textContent), 100);
</script>
</body>
</html>
<!-- Output:
Rendered: SendSaved Ada
console: Saved Ada
-->
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- .prevent भूल जाना
- submit की बजाय एक click handler इस्तेमाल करना
- loading या error states न दिखाना
चैप्टर सारांश
- @submit.prevent form handle करता है
- v-model bindings से data पढ़ें
- Loading और error states दिखाएँ
- Success के बाद fields reset करें
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: