← Back to Vue.js Course | Chapter 5: Forms | Lesson 6 of 6

Form जमा करना

Vue में एक form का submit event handle करें और browser को page reload करने से रोकें।

In this page:

  1. Form Submission
Syntax
markup
<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

markup
<!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. #}
आम गलतियां
  1. .prevent भूल जाना
  2. submit की बजाय एक click handler इस्तेमाल करना
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.