Copy text to clipboard using Vuejs?

Asked

Viewed 845 times

0

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

I’ve found several examples I pure JS, but in the project in question is being used Vuejs and I found nothing to 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.');
  }
});

There is a way for me to use the code above in Vuejs??

Note: original link of the code of the above example here

1 answer

1

Can 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>
<div id="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 the refs in order to access the element within the Vue instance

  • I tried the code you made above, however it is giving error: copyTextarea.select() is not a function, can it be the Quasar Framework interfering?? I saw that it adds several div's in HTML...

  • Yes, in my case I put ref="linhaDigitavel" both in HTML and function

  • It’s just like that inside the function

  • https://jsfiddle.net/capha10u/

  • The problem is that I am not only using Vue, but Quasar, which greatly alters the HTML of Vue, but I will give a complement there...

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.