[Vuejs]-How can I get value when submit form on the vue component?

2👍

From the official docs Form Input Components using Custom Events:

  • Know that v-model in the parent is the same as:

      <child-component
         v-bind:value="something"
         v-on:input="something = $event.target.value">
    

So when using v-model you are actually "sending" a value prop and "expecting" an input event.

To make that happen, then, in the child component do:

  • Declare the prop value
  • Change the <input> to have as :value the value prop declared above
  • Change the <input> to emit an input event to its parent when changing value

Final template:

<template>
    <div class="form-group">
        <label :for="id" class="col-sm-3 control-label"><slot></slot></label>
        <div class="col-sm-9">
            <input :type="type" :name="name" :id="id" class="form-control" :value="value" @input="$emit('input', $event.target.value)">
        </div>
    </div>
</template>
<script>
    export default {
        props: {
            'id': String,
            'name': String,
            'type': {
                type: String,
                default() {
                    if(this.type == 'number')
                        return 'number'
                    return 'text'
                }
            },
            'value': String,
        }
    }
</script>

Leave a comment