0
votes

I've got a parent component with a submit button

<v-card flat>
  <child-component :submit="submit()"></child-component>
  <v-card-actions>
    <v-spacer></v-spacer>
    <v-btn @click="submit" type="submit">Change password</v-btn>
  </v-card-actions>
</v-card>

and a child component with a form that has a @submit.prevent that I need to call whenever I click the button on the parent:

<v-form @submit.prevent="submit">....</v-form>

My submit() is on the parent, it's just a simple function that submits the data to a database. It requires parameter X. The reason I have a @submit.prevent on the child form is that I can press enter to submit the form.

How can I pass the submit() as a prop to the child? Or how can I call submit from the child component?

3

3 Answers

0
votes

The child should emit an event on submit:

<v-form @submit.prevent="$emit('submit')">....</v-form>

And the parent can listen for that event to call the method:

<child-component @submit="submit"></child-component>
0
votes

You can use ref

      <v-card flat>
        <child-component ref="form"></child-component>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn @click="submit" type="submit">Change password</v-btn>
        </v-card-actions>
      </v-card>


 methods: {
        submit() {
          this.$refs.form.submit()
        }
      },
0
votes

You can use slots to pass your submit button from parent to child form and it will work. Also you can define default template, if no slots is passed.
So you will be able to use form itself, without passed submit button (it will have it's own, default, button), or pass slot with any button you need.
Then you just listen to submit event of form (submit.prevent on form) and do whatever you want in parent component.

Vue.component('form-component', {
  template: `
    <form @submit.prevent="submitEvent">
      <input type="text" v-model="value"/>
      <slot>
        <button type="submit"> Default Submit </button>
      </slot>
    </form>
  `,
  data: () => ({
    value: 'Hello Vue!'
  }),
  methods: {
    submitEvent(e) {
      this.$emit('submit', e);
    }
  }
});

const app = new Vue({
  el: '#app',
  methods: {
    submitForm(e) {
      console.log(e.target);
    }
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <form-component @submit="submitForm">
    <template v-slot>
      <button type="submit"> Submit </button>
    </template>
  </form-component>
</div>