Once the form is submitted, Vue automatically resets all the data

export default {
  data() {
    return {
      usrName: null,
      pass1: null,
      pass2: null,
      regState: {stateCode:-1},
    }
  },
  methods: {
    register: function () {
        this.axios.post("/login/", { baseURL: 'http://127.0.0.1:3000', usrName: this.usrName, passWord: this.pass1 }).then((response)=>{
          console.log(response.data)
          this.$store.state.sysDecision.usrDecision = 2
        })
      }
    }
  }
}
</script>


<template>
  <XAIHeader :registerActive="true"></XAIHeader>
  <div class="container">
    <form class="w-50 mx-auto pt-5" style="padding-bottom: 400px;">
      <h5 class="mb-3">register</h5>
      <div>
        <label class="form-label">user name</label>
        <input v-model="usrName" type="text" class="form-control" required>
      </div>
      <div>
        <label class="form-label">pass word </label>
        <input v-model="pass1" type="current-password" class="form-control" required>
      </div>
      <div>
        <label class="form-label">repeat pass word</label>
        <input v-model="pass2" type="new-password" class="form-control" required>
      </div>
      <div class="mt-3">
        <button @click="register" class="btn btn-primary" type="submit">register</button>
      </div>
    </form>
    {{ this.$store.state.sysDecision.usrDecision}}
  </div>
</template>

I have encountered an issue where the form data gets reset to initial values after successfully submitting a post request using axios in Vue.js. Even the data stored in vuex also resets to default values. How can I prevent this from happening and retain the previous form data after it has been submitted?

Answer №1

To solve this issue, I replaced the <form></form> with <div></div>. It appears that using the <form></form> tag leads to unavoidable page reloading.

Answer №2

@submit.prevent="register"

give this a shot, it might just do the trick.

<template>
  <XAIHeader :registerActive="true"></XAIHeader>
  <div class="container">
    <form @submit.prevent="register" class="w-50 mx-auto pt-5" style="padding-bottom: 400px;">
      <h5 class="mb-3">register</h5>
      <div>
        <label class="form-label">enter your username</label>
        <input v-model="usrName" type="text" class="form-control" required>
      </div>
      <div>
        <label class="form-label">password </label>
        <input v-model="pass1" type="current-password" class="form-control" required>
      </div>
      <div>
        <label class="form-label">confirm password</label>
        <input v-model="pass2" type="new-password" class="form-control" required>
      </div>
      <div class="mt-3">
        <button class="btn btn-primary" type="submit">register</button>
      </div>
    </form>
    {{ this.$store.state.sysDecision.usrDecision}}
  </div>
</template>

for more information check out https://vuejs.org/guide/essentials/event-handling.html#event-modifiers

Answer №3

Once you have submitted the form data, remember to reset your v-model data to null in order to clear the form.

Resetting: this.usrName = null

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best method for eliminating the default title in selectpicker?

I'm currently working on integrating angular selectpicker into my project. Initially, everything was displaying correctly as shown below: <select class="selectpicker"> <option>Mustard</option> <option>Ketchup</opti ...

Is there a way to streamline the import process for material-ui components?

Is there a shortcut to condense all these imports into one line? As a newcomer to react, I've noticed that every component must be individually imported, especially when it comes to CSS components. Could you provide me with a suggestion on how to st ...

Is there a way to verify if all the values in an array of objects are identical?

In this scenario, my array consists of entries with identical address IDs but different phone types and numbers. I am in need of assistance with iterating through the array to extract the phone type and number when the address ID matches. I seem to encount ...

Display or conceal a div depending on the value of an integer stored in the $scope variable

Consider the ng repeat pattern below: <div class="presentForm" id="presentForm{{$index}}" ng:repeat="slide in slides" style="display: block;"> <img id ="presentationSlide" ng-src='{{slide}}' style="height: 300px" width ...

"Encountered an unexpected token when using an object parameter in a React function

I am facing an issue with a function I have implemented in React Native. const HandleConfirmApplication = async ( opts: { isInvite: boolean, confirmationCheckValues: () => any, confirmPopUp: () => any, loadingApply: () => any, ...

Determine which children should be displayed in a Kendo treeview based on the field titled "ParentId"

After converting a list of records into JSON format, I am looking to transform this data into a hierarchical KendoTreeView. Here is the JSON data: [ { "id": 1, "name": "A", "parentID": 0, "hasItems": "true" }, { "id": 2, "name": "B", "parentID": 1, "has ...

Step-by-step guide on uploading a local JSON file to Google Maps

I am in the process of creating a map for my website using the Google Maps JavaScript API. The map includes a local JSON layer that outlines a specific polygon area on the map. Everything worked perfectly when I tested it within Visual Studio, but when I t ...

How to surround values and keys with double quotes using regular expressions in JavaScript

I am in need of a valid JSON format to request ES. I currently have a string that looks like this: { time: { from:now-60d, mode:quick, to:now } } However, when I attempt to use JSON.parse, I encounter an error because my ...

Tips for transforming an Observable stream into an Observable Array

My goal is to fetch a list of dogs from a database and return it as an Observable<Dog[]>. However, whenever I attempt to convert the incoming stream to an array by using toArray() or any other method, no data is returned when calling the retrieveDo ...

What is the reason the useEffect hook does not function properly with a state variable within context?

Check out my code here. I'm trying to display the content of the array testingData, but it's not showing up. If I remove the useEffect hook, it works fine. Can you help me understand why and how to fix it? ...

Is there a way for me to display the image name at the bottom before uploading it, and have a new div created every time I upload an image?

Is there a way to display the image name at the bottom and have it create a new div every time an image is uploaded? I would appreciate any help with this... <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstra ...

Ways to ensure your Javascript code only runs based on the specific browser

I need a Javascript code to run depending on the browser version. Specifically, if the browser is not IE or is IE 9+, one piece of Javascript should be executed. If the browser is IE8 or lower, another piece of Javascript should be executed. My attempt to ...

JSON payload with an array that includes nested JSON objects

I am struggling with JSON objects and need to create a JSN structure similar to the following: { name: 'root', children: [ name: 'son1', children: [....] ] } Could someone please guide me on how to construct it using Java ...

Upon exchanging data with the router located in the navigation bar, a continuous loop occurs as I initiate the download operation involving the electron-dl and electron-download-manager tools

When I switch to the router in the navbar, a loop occurs when I try to initiate the download process. I've been struggling with this issue for the past 2 days and can't seem to find a solution. function downloaddosya1() { console.log("Fi ...

Tips for consolidating outputs from three different APIs using JavaScript and AJAX? [Pseudo code example]

For my school project, I am working on an e-commerce aggregator site where I need to combine product data from 3 different APIs (like Aliexpress and Amazon) into one homepage. Although I can retrieve results from each API individually, I'm facing chal ...

Displaying multi-dimensional arrays through the console in JavaScript and showcasing their elements

My array is supposed to have 140 indexes in a single format like this: array:[0-140] //however, it currently appears as: array: [ 0: [0-99], 1: [100-140] ] I've confirmed multiple times that it is just one array of objects. Why is it s ...

Typescript raises an issue regarding a React component's optional prop potentially being undefined

I have a basic React component that looks like this: interface ComponentProperties { onClick?: () => void; } const CustomComponent = (properties: ComponentProperties) => { if (!properties.onClick) { return <></>; } ...

Creating a full-width tab card with Bootstrap-Vue: A step-by-step guide

I stumbled upon something similar in the documentation for bootstrap-vue: A card with tabs: Now, how can I style the tabs to look like this: This is my current code: <b-card no-body> <b-tabs card> <b-tab title="Tab 1" active& ...

problem with accessing a website input area

Upon clicking outside the "subheader", I need to display the words "register" and "login" again, unless something is typed into the input fields... that's all there is to it, just click outside the subheader $(document).ready(function() { $(&ap ...

Retrieving properties from video element following webpage loading

I am trying to access the 'currentSrc' value from a video object in my code. Here is what I have: mounted: function () { this.$nextTick(function () { console.log(document.getElementById('video').currentSrc) }); }, Despi ...