Skip to main content
The 2024 Developer Survey results are live! See the results
Rollback to Revision 1
Link
David Makogon
  • 70.7k
  • 21
  • 144
  • 191

VUE js: prevent a function to run once when initially loaded/mounted [Fixed]

edited title
Link

VUE js: prevent a function to run once when initially loaded/mounted [Fixed]

Source Link

VUE js: prevent a function to run once when initially loaded/mounted

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.