0

I'm trying to create a form that sends the submitted data into a database: I'm new in vue and still reading the documentation, if the answer is in the documentation please do remind me. The below is a summarize of my code

<template>
      <form>
        <input type="text" required>
        ...
      </form>
    <button @click="handleSubmit">Submit</button>
</template>


<script>
import uploadData from '../path';
import { ref } from 'vue';

export default {
    name: "Upload",
    setup() {
      ...
      const handleSubmit = () => {
        data = {
          "name": "",
          ...
        }
        uploadData(data)
      }
      )
      
      return { handleSubmit }
    }
}
</script>

Of course I expected the form to not submit anything when initially loaded I tried it in my local sever, and when I opened it in a browser, the console logs Data Uploaded which is a line written in the uploadData. This means that the uploadData, handleSubmit, and the setup() ran once when the component first mounted (right?). This means it will submit an empty form to my database each time before actually filling the form. How can I fix this? thank you.

I've read the watcher documentation and tried to change the logic that if when the button is clicked a value that the watcher see changes, and so the watcher will run and submit the form. But the uploadData still run once when mounted.

2 Answers 2

1

You can use @submit.prevent="handleSubmit"

<template>
  <form @submit.prevent="handleSubmit">
    <input type="text" v-model="formData.name" required />
    <!-- Add other form fields with v-model bindings here -->
    <button type="submit">Submit</button>
  </form>
</template>


<script>
import uploadData from '../path';
import { ref } from 'vue';

export default {
  name: "Upload",
  setup() {
    const formData = ref({
      name: '',
      // Initialize other form fields here
    });

    const handleSubmit = () => {
      if (formData.value.name) { // Ensure required fields are not empty
        uploadData(formData.value).then(() => {
          console.log("Data Uploaded");
        }).catch(err => {
          console.error("Error uploading data:", err);
        });
      } else {
        console.error("Form is not completely filled out.");
      }
    };

    return { formData, handleSubmit };
  }
}
</script>

If that is still not working, let me know that.

Thank you

1
  • I tried it, and it still fail. I've debug it abit more detail and found that the uploadData() ran even before the setup() ran. At least it's clear now that the handleSubmit didn't ran Commented Jul 6 at 5:02
0

Sorry, the problem is solved now. It was in the uploadData.js

I exported not the function but the function eval. export default uploadData()

i changed it to export default uploadData

and the problem is fixed

Not the answer you're looking for? Browse other questions tagged or ask your own question.