Home > Enterprise >  Method is not working properly onClick submit
Method is not working properly onClick submit

Time:06-29

Empty form object is saving in array on submit. when i submit the button. I want to add form object in array and then reset values of form object. The problem is when I click the submit button first it reset then push object into array.

<template>
  <div >
    <form @submit.prevent="addIntoArr">
      <input type="text" v-model="form.input1" />
      <p>{{ form.input1 }}</p>
      <button type="submit">add me</button>
    </form>
    <!-- <Apply /> -->
  </div>
</template>

<script>
// import Footer from "../components/footerFr/header.vue";

// import Apply from "../components/apply.vue";

export default {
  name: "Home",
  components: {
    // Apply,
  },
  data: () => {
    return {
      arr: [],
      form: {
        input1: "",
        input2: "",
        input3: "",
      },
    };
  },
  methods: {
    addIntoArr() {
      console.log("form", this.form);
      this.arr.push(this.form);
      console.log("arr", this.arr);
      this.form.input1 = "";
    },
  },
};
</script>

<style lang="scss" scoped>
.home {
  width: 100%;
}
input {
  border: black 1px solid;
}
button[type="submit"] {
  background-color: red;
}
</style>

Suppose i type input1="ddjsnkjfns" and then when I click submit button. it suppose to print form object like this

form={
   input1:"ddjsnkjfns",
   input2:"",
   input2:""
}

Then push this object into arr array.

But it prints empty object like this

form={
   input1:"",
   input2:"",
   input2:""
}

and then save empty object into arr array.

before submit enter image description here

after submit enter image description here

CodePudding user response:

Reason for what you see is most browser today when you log an object show the live version (source) - so what you see is not the value at the time log statement was executed

To workaround this, you should log stringified value: console.log(JSON.parse(JSON.stringify(obj)))

Second problem is you seem not understand how objects work in JS. Following code:

this.arr.push(this.form);
this.form.input1 = "";
  1. pushes the reference to form object into the array
  2. modifies the same object (only through different reference)

Read more

So the correct way is actually to make a copy of the object when pushing (by using destructuring in my example):

this.arr.push({...this.form});
this.form.input1 = "";

  • Related