Search code examples
formsvue.jsstorevuex

How to trigger a form inside a component from VueX store


I'm calling an action in the store to send data to an API. This call is triggered from a button in FormComponent from @click :

<button type="button" @click="$store.dispatch('saveStoreDatas')">Click me</button>

How can I submit the parent form of button (omitted code) ? I cannot use a ref because it's inside a component.

Thank you !


Solution

  • Do you need to dispatch an action and submit the form? Normally you can just have form data in the store and send it in the action.

    If you really need to submit the form, emit an event in the child component and listen for the event in the parent component.

    Child component will goes like this.

    <!-- child component template -->
    <button type="button" @click="handleClick">Click me</button>
    
    // child component script
    methods: {
        handleClick () {
            this.$store.dispatch('saveStoreDatas')
            this.$emit('clickSubmit')
        }
    }
    

    And this is its parent.

    <!-- parent template -->
    <form ref="form">
        <child-component @clickSubmit="submitForm">
    </form>
    
    // parent component script
    methods: {
        submitForm () {
            this.$refs.form.submit()
        }
    }