3
votes

I have a form in my child component:

<form @submit="submitForm">
  <input type="text" v-model="textInput" />
</form>

export default {
  name: "childComp",
  data: function() {
    return {
     textInput: ""
    }
  }
}

Now from my parent component I have a button and I need to click on that button to get the child form data.

<button type="button" @click="getFormData()"> click </button>

export default {
  name: "ParentComp",
  data: function() {
    return {
     formData: []
    }
  },
  methods: {
    getFormData(d) {
      formData.push(d);
      console.log(d)
    }
  }
}

Appreciate your help.

2
The recommended way to handle complex state management like this is to use Vuex.Joshua Minkler
@JoshuaMinkler is this complex?André Werlang

2 Answers

3
votes

Even though you got it solved by using $ref, i would recommend utilizing the power of a v-model implementation into your custom component.

This is a more clean approach, and by doing this, you'll always have the form data at hand, instead of having to actually retrieve it when you want to use it.

It can be done by doing the following:

Parent

<button type="button" @click="getFormData()"> click </button>
<childComp v-model="formData" />

export default {
  name: "ParentComp",
  data: function() {
    return {
     formData: {}
    }
  },
  methods: {
    getFormData() {
      console.log(this.formData)
    }
  }
}

Child

<form>
  <input type="text" v-model="selected.text" />
</form>

export default {
  name: "childComp",
  props: ['value'],
  computed: {
    selected: {
      get() {
        return this.value;
      },
      set(value) {
        this.$emit('input', value);
      } 
    }
  }
}
-1
votes

I found the solutions using ref="". Not sure how complex it will get in future.

Here is what I did.

My parent component:

<button type="button" @click="getFormData()"> click </button>
<childComp ref="childComp" />

export default {
  name: "ParentComp",
  data: function() {
    return {
     formData: []
    }
  },
  methods: {
    getFormData() {
      const data = this.$refs.childComp.submitForm()
      formData.push(data);
      console.log(data)
    }
  }
}

My child component:

<form @submit="submitForm">
  <input type="text" v-model="textInput" />
</form>

export default {
  name: "childComp",
  data: function() {
    return {
     textInput: ""
    }
  },
  submitForm() {
    return this.form;
  }
}