Home > front end >  Nuxtjs/Vuejs Form data are lost on navigating to different route and coming back to previous route u
Nuxtjs/Vuejs Form data are lost on navigating to different route and coming back to previous route u

Time:09-17

I am developing a Nuxtjs application and in that, I have a form, the user fills in the information and submits the form. After submission user is navigated to a different route. Now if the user clicks on the back button of browser then the user has navigated to form again but the data are reset in the field.

I want to ensure that when the user clicks on the browser back button then the data which was filled in by the user to be retained. I tried searching and found that we need to use autocomplete=on and I tried that but it's not working for me. Can someone please help me with how can I retain the user-provided information inform when the user navigates back to the route.

<template>
  <div id="eventForm" class="row" style="margin-top:1%">
    <form ref="testDataForm" class="form-horizontal" autocomplete="on" @submit.prevent="formSubmit">
      <input
        v-model="formData.eventCount"
        type="number"
        class="form-control"
        required
      >

      <b-form-select v-model="formData.optionsSelector" class="form-control">
        <b-form-select-option value="null" disabled selected>
          Choose
        </b-form-select-option>
        <b-form-select-option value="value1">
          Text1
        </b-form-select-option>
        <b-form-select-option value="value2">
          Text2
        </b-form-select-option>
      </b-form-select>
      <button type="submit" class="btn btn-success">
        Submit
      </button>
    </form>
  </div>
</template>

<script>
export default {
  data () {
    return {
      formData: {
        optionsSelector: null
      }
    }
  },
  methods: {
    formSubmit () {
      this.$router.push('/GenerateTestData')
      // this.$router.push({ path: '/GenerateTestData' })
    }
  }
}
</script>

<style>

</style>

CodePudding user response:

You need to persist your data in some way. Either by getting the state back again (formData.optionsSelector) or by storing it in cookies/localStorage/else.

https://stackoverflow.com/a/66872372/8816585

So if you want to have it when you come back, you need to have a getter of the state rather than having it defaulting to null when the component is mounted.

À combo of a computed Vuex could be the way too.

CodePudding user response:

You should use "keep-alive" to keep the rendered element.If you are using nuxt.js add this in your default.vue file: https://nuxtjs.org/docs/2.x/features/nuxt-components

<template>
    <v-app dark>
        <v-main>
            <v-container class="ma-0 pa-0" id="appContainer" fluid>
                <nuxt keep-alive/>
            </v-container>
        </v-main>
    </v-app>
</template>
  • Related