Skip to content
Advertisement

Retain filled form fields on page refresh in Vue

The issue I am facing here is, I am not able to figure out how can I retain the values in the form on page refresh. Each time I refresh the page all the filled values in the form are gone.

Help me resolve this issue. I was thinking of using localStorage but not sure how I can implement it.

   <template>
     <v-card class="mb-12">
       <v-form :model='user' class="content-padding" ref='pdfInputs'>
            <div class="section-header">
              User
            </div>
            <v-container fluid>
             <ul>
              <li v-for="(input, index) in user.inputs">
               <input type="text" v-model="input.one"> - {{ input.one }}  
               <input type="text" v-model="input.two"> - {{ input.two }}
               <button type="button" @click="deleteRow(index)">Delete</button>
              </li>
             </ul>   
            </v-container>
       </v-form>
     </v-card>
   </template>  


<script>
 export default {
  data () {
    return {
     user: {
      inputs: []
     }
    }
  }
  methods: {
    addRow() {
      this.user.inputs.push({
        one: '',
        two: ''
      })
    },
    deleteRow(index) {
      this.user.inputs.splice(index,1)
    }
  }
 }
</script>

Advertisement

Answer

There is watch functionality in vue

export default {
  data () {
    return {
     user: {
      inputs: []
     }
    }
  },
  mounted() {
    this.user.inputs = JSON.parse(localStorage.getItem('form')) || [];
  },
  watch: {
        user: {
            handler: function() {
                localStorage.setItem('form', JSON.stringify(this.user.inputs));
            },
            deep: true
        }
    },
  methods: {
    addRow() {
      this.user.inputs.push({
        one: '',
        two: ''
      })
    },
    deleteRow(index) {
      this.user.inputs.splice(index,1)
    }
  }
 }
Advertisement