6

In a Vue app I have a paste listener on a textarea with the intention to run validation code when the user pastes data into this field. When I log the paste event I can see in the console that the data that was pasted into the field is there under event -> target -> value. I can't seem to access this with event.target.value though. What am I doing wrong?

Minimal example:

<div id="app">
  <textarea name="myField" @paste="onPaste"></textarea>
  <p>Field name: {{ fieldName }}</p>
  <p>Pasted data: {{ pasted }}</p>
</div>
var app = new Vue({
  el: '#app',
  data: {
    fieldName: '',
    pasted: ''
  },
  methods: {
    onPaste(event){
        console.log(event)
        this.message = event.target.name
        this.paste = event.target.value
    }
  }
})

https://jsfiddle.net/feg8pcmv/

Aymen TAGHLISSIA
  • 1,675
  • 13
  • 30
jonas87
  • 672
  • 2
  • 8
  • 22

2 Answers2

3

First of all, your jsfiddle has a minor typo (this.paste instead of this.pasted).

Secondly, you need to use the "getData" method from the clipboardData property to access the text.

https://developer.mozilla.org/en-US/docs/Web/API/Element/paste_event

this.pasted = event.clipboardData.getData('text')

https://jsfiddle.net/zfuwy9ep/

That said, if you want to get the whole string inside the text area after something was pasted, you could wait until the current items in the event queue have been resolved, and read the value of the textarea afterwards

setTimeout(() => {
   console.log('textarea contents', event.target.value);
})

https://jsfiddle.net/cjq1bw5u/

Alberto Rivera
  • 3,652
  • 3
  • 19
  • 33
2

Currently (as of now) according to MDN docs regarding onpaste event

The paste event fires when the user attempts to paste text.

Note that there is currently no DOM-only way to obtain the text being pasted; you'll have to use an nsIClipboard to get that information.

And since Clipboard API/events are in draft, supporting older browsers may not be achieved.

One not so neat solution is to use setTimeout:

  methods: {
    onPaste(event){
      setTimeout(() => {
      console.log(event);
      this.fieldName = event.target.name;
      this.pasted = event.target.value }, 100);
    }
  }

More info can be found here

ambianBeing
  • 3,449
  • 2
  • 14
  • 25