Search code examples
javascriptvue.jsvuejs2vue-componentvuex

How to submit a form using vue.js 2?


My view blade laravel like this :

<form slot="search" class="navbar-search" action="{{url('search')}}">
    <search-header-view></search-header-view>
</form>

The view blade laravel call vue component (search-header-view component)

My vue component(search-header-view component) like this :

<template>
    <div class="form-group">
        <div class="input-group">
            <input type="text" class="form-control" placeholder="Search" name="q" autofocus v-model="keyword">
            <span class="input-group-btn">
                <button class="btn btn-default" type="submit" id="submit-search"><span class="fa fa-search"></span></button>
            </span>
            <ul v-if="!selected && keyword">
                <li v-for="state in filteredStates" @click="select(state.name)">{{ state.name }}</li>
            </ul>
        </div>
    </div>
</template>
<script>
    export default {
        name: 'SearchHeaderView',
        data() {
            return {
                baseUrl: window.Laravel.baseUrl,
                keyword: null,
                selected: null,
                filteredStates: []
            }
        },
        watch: {
            keyword(value) {
                this.$store.dispatch('getProducts', { q: value })
                .then(res => {
                    this.filteredStates = res.data;        
                })
            }
        },
        methods: {
            select: function(state) {
                this.keyword = state
                this.selected = state
                document.getElementById('submit-search').submit()
            },
            input: function() {
                this.selected = null
            }
        },    
    }
</script>

I want to submit the form when user click the keyword

I try document.getElementById('submit-search').submit()

But on the console exist error like this :

TypeError: document.getElementById(...).submit is not a function

How can I solve this error?


Solution

  • You need to call submit() on the <form> element (which is the root element of the component):

    this.$el.submit();
    

    EDIT: Since you have updated your question, the above no longer applies.

    To trigger a button click, just call click() on the button element:

    <button ref="submitButton">Foo</button>
    
    this.$refs.submitButton.click();
    

    This is fine if your components are meant to be tightly-coupled, otherwise a cleaner solution would be to $emit an event from your <search-header-view> component and respond to it in the parent component, like this:

    this.$emit('submit');
    

    In parent component:

    <search-header-view @submit="submit">
    
    methods: {
      submit() {
        // Submit the form manually here (add a ref to your form element)
        this.$refs.form.submit();
      }
    }