Denys
Denys

Reputation: 333

Get data to Parent component from multi child components

I need to collect data from all child components and get it in Parent component. For example i have a form component with "Save" button. Once i click on "Save" button i need all child component send me all data that an user put there.

<Form>
  <Name />
  <DatePicker />
  .....
</Form> 

So the main component is Form and it has several child components. Once i click on "Save" in i need to get child components data in Form.

I am thinking about giving "ref" to all child component and call their own methods in Parent once i click on "Save" inside Form. In those methods i will collect all data and fire events with this.$emit there i can send to parent the data i have collected.

Is that a good solution?

Or maybe better to use EventBus?

Upvotes: 0

Views: 561

Answers (1)

Gander
Gander

Reputation: 1991

I prefer bind over emit.

Vue.component("InputField", {
  template: `<input v-model="syncedValue" />`,
  name: "InputField",
  props: {
    value: String
  },
  computed: {
    syncedValue: {
      get() {
        return this.value;
      },
      set(v) {
        this.$emit("input", v);
      }
    }
  }
});

Vue.component("Form", {
  template: `<div><InputField v-model="name"/><InputField v-model="surname"/><button @click="save">Save</button></div>`,
  name: "Form",
  data() {
    return {
      name: "",
      surname: ""
    };
  },
  methods: {
    save() {
      alert(`${this.name} ${this.surname}`);
    }
  }
});

new Vue({
  template: `<Form></Form>`
}).$mount("#app");
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>

Upvotes: 0

Related Questions