1
votes

I have a parent component and I am assigning values in child component form. But after submitting the form I want form field should be empty.

I am using resetFields function for resetting value but when I am using these function it is setting last value, what I send it from parent component instead of reset value I want form fields should be empty.

<script>
    export default {
        props: ["empData"],
        data {
            return() {
                empInfo: {
                    name: "",
                    id: null,
                    age: null
                }
            }
        },
        methods: {
            getUserData() {
                if (response.status == "SUCCESS") {
                    this.$refs['empInfo'].resetFields();
                }
            }
        }
        watch: {
            empData: immediate: true,
            handler() {
                this.empInfo = this.empData;
            }
        }
    }
</script>
<template>
  <div>
    <el-form :label-position="labelPosition" :model="empInfo" status-icon :rules="rules" ref="empInfo">
      <el-form-item label="Employee Name" prop="name">
        <el-input v-model="empInfo.markupName"></el-input>
      </el-form-item>
      <el-form-item label="EMployee Id" prop="id">
        <el-input v-model="empInfo.id"></el-input>
      </el-form-item>
      <el-form-item label="Employee Age" prop="age">
        <el-input v-model="empInfo.age"></el-input>
      </el-form-item>
      <el-button @click="getUserData">Submit</el-button>
  </div>
</template>
2
You could just write a reset method in your component and initialize the values (with either empData or empty values) and call this method on created() and then recall this method on reset or after the data changes.ssc-hrep3

2 Answers

0
votes

The Element UI form seems to latch onto the data it gets initialized with, and resetFields() reinitializes the form with that data. You could defer the watcher until the next tick so that the component's initially empty empInfo could be propagated to the Element UI form as initial data, which would then be used in resetFields().

watch: {
  empData: {
    immediate: true,
    handler(value) {
      this.$nextTick(() => {
        if (value) {
          this.empInfo = value;
        }
      });
    }
  }
}

demo

0
votes

If you use Parent and Child component, it is good practise to emit data as output to parent component and then process data. This parent child pattern is good for making dynamic form. Reset method cleares your form.

getUserData() {
        if (this.$refs.empInfo.validate()) {
            this.$emit('get-user-data', this.empInfo);
            this.$refs.empInfo.reset();
        }
}