Search code examples
htmlvue.jsvuejs2quasar-framework

Vue.js -How can I submit a form with the Enter key?


So simple input

<input ref="input" class="terminal-input" autofocus
  v-model="message" type="submit" @submit.prevent="printToConsole"/>

When added type="submit" I can't type in the input anymore. It just changes into a button! So I've found a solution to just make a form, add a button (make it submit) and hide the button.

 <form>
      <input ref="input" class="terminal-input" autofocus v-model="message"/> 
      <q-btn type="submit" @click="printToConsole" v-show="false"/>
 </form>

Can I somehow do this but with input only? (So no hiding button stuff)


Solution

  • The @submit event should be added to the form element:

     <form  @submit.prevent="printToConsole">
          <input ref="input" class="terminal-input" autofocus v-model="message"/> 
          
     </form>
    

    Vue.config.devtools = false;
    Vue.config.productionTip = false;
    
    new Vue({
      el: '#app',
    
      data() {
        return {
          message: ''
        }
      },
      methods: {
    
        printToConsole() {
          console.log(this.message)
        }
      }
    })
    <link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
    
    
    <div id="app" class="container">
      <form @submit.prevent="printToConsole">
        <input ref="input" class="terminal-input" autofocus v-model="message" />
    
      </form>
    </div>