10

I have a text input field, something like:

        <q-input
          @blur="checkTextAnswer"
          @keyup.enter="submit"
          @keydown="checkEnterKey"
          v-model.trim="textInput"

When the user hits enter I want to treat it like a submit, ie to handle the input and not add an extra newline in the text.

It's a bit like preventDefault from JQuery days. I did find this: https://quasar-framework.org/components/other-utils.html but seems for more general DOM events

I also tried just modifying the string (str.replace the newline) but even that hack has an ugly delay.

dcsan
  • 11,333
  • 15
  • 77
  • 118

1 Answers1

14

You need to use the vue event modifier ".prevent" in your event. It also needs to be a @keydown event since the "add newline" event is called with @keydown events in inputs of type "textarea".

The solution would be:

     <q-input
      type="textarea"
      @keydown.enter.prevent="submit"
      v-model.trim="textInput"

EDIT:

The 'submit' is a method that you have to define. Here's an example I made in codepen:

Codepen example

If you instead want to submit a form when pressing enter you can just use javascript for this.

this.$refs[refKeyYouGaveToYourForm].submit()
tony19
  • 125,647
  • 18
  • 229
  • 307
Jasqui
  • 391
  • 2
  • 5
  • However, it didn't work ... >> ` [Vue warn]: Property or method "submit" is not defined on the instance ... ` actually in this case I just have an input area and no form. I just want to strip the linefeeds appearing on the input from appearing. – dcsan Dec 08 '18 at 04:56
  • Oh I just assumed that 'submit' was a method of yours where you handled whatever you wanted to do when button was pressed in your component/vue instance. In that case you'll have to create a method and call it in the keydown event. In theory with the ".enter.prevent" no newline character should be created. If you want to set the variable textInput only when pressing enter instead of it updating reactively then you should use ":value" instead of "v-model" – Jasqui Dec 08 '18 at 15:54