Copy text to clipboard using VueJS?

0

In the return of a request the digitable line of a ticket is coming and I assign this digitable line to a variable, but what I want to do now is to copy that digitable line to the clipboard, so that the user can paste (ctrl + V) anywhere else.

I have already found several examples of pure JS, but in the project in question VueJS is being used and I did not find anything that would help me.

Example in pure JS:

var copyTextareaBtn = document.querySelector('.copiar');

copyTextareaBtn.addEventListener('click', function(event) {
  var copyTextarea = document.querySelector('.textarea');
  copyTextarea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'sim!' : 'não!';
    alert('Texto copiado? ' + msg);
  } catch (err) {
    alert('Opa, Não conseguimos copiar o texto, é possivel que o seu navegador não tenha suporte, tente usar Crtl+C.');
  }
});

Is there a way I can use the above code in VueJS ??

Note: Original example code link above #

    
asked by anonymous 09.02.2018 / 18:11

1 answer

1

Easily adapt to VueJS

var vue = new Vue({
    el: "#app",
    methods: {
      copy: function() {
        var copyTextarea = this.$refs.copiar
        
        copyTextarea.select();

        try {
          var successful = document.execCommand('copy');
          var msg = successful ? 'sim!' : 'não!';
          alert('Texto copiado? ' + msg);
        } catch (err) {
          alert('Opa, Não conseguimos copiar o texto, é possivel que o seu navegador não tenha suporte, tente usar Crtl+C.');
        }
      }
    }
})
<script src="https://cdn.jsdelivr.net/npm/vue"></script><divid="app">
<textarea class="textarea" ref="copiar">Vamos copiar este texto?</textarea>
<hr>
<button @click="copy">Copiar</button>
</div>

The only detail is the use of refs to be able to access the element within the instance of vue

    
09.02.2018 / 19:02