Search code examples
vue.jsbootstrap-modalbootstrap-vue

How to submit a form from another component when the modal OK button is clicked (bootstrap vue)


In my Vue app, I have a component that handles a simple form named TodoForm. Using bootstrap-vue, i would like to submit this form when the OK button of a bootstrap modal is pressed.

The code looks like this:

<b-modal id="todo-form-modal">
    <todo-form />
</b-modal>

I don't want to put the modal component inside the TodoForm component since the TodoForm component only handles the form behavior, not the container where it is displayed.

I could also disable the OK button and put a button inside the form myself, but i'm sure there is a proper, a better way to submit this form (it is more like an exercise than a real project with an actual deadline).

I found the @ok event in the doc (triggered when the OK button is pressed), which is nice but i'm struggling to understand how i could use it to call a onSubmit() method inside the TodoForm.

For instance, it looks like this:

<b-modal id="todo-form-modal" @ok="something">
    <todo-form />
</b-modal>

Ideally, the @ok="something" should call a method inside the TodoForm component.

How can I achieve this the right way ?


Solution

  • Expanding on @mapawa's answer:

    <template>
      <b-modal ... @ok="handleOk">
        <todo-form ref="todoform" ...></todo-form>
      </b-modal>
    </template>
    
    <script>
    import TodoForm from 'somewhere/todoform'
    
    export default {
      components: { TodoForm },
      methods: {
        handleOk(bvEvt) {
          // This assumes the root element of the todo form is the <form>
          this.$refs.todoform.$el.submit()
          // Alternatively, if your Todo Form exposes a submit method
          this.$refs.todoform.submit()
        }
      }
    }
    </script>