首页 > 解决方案 > 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)

标签: htmlvue.jsvuejs2quasar-framework

解决方案


@submit事件应添加到表单元素中:

 <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>


推荐阅读