Home > Mobile >  How can I create a copy button directly from same button Vuejs
How can I create a copy button directly from same button Vuejs

Time:11-19

Hi I have a code like this in VueJs:

methods: {
   copyUrl(data) {
      console.log(data);
      data.select();
      document.execCommand("copy");
   }
}

My button is:

 <button v-on:click="copyUrl('1234')" >
     <i ></i>
 </button>

I wonder how can I copy the 1234? I mean I need to create a url copy button.

Thanks

CodePudding user response:

Take some inspiration from the answer to this question How do I copy to the clipboard in JavaScript? (see the section named Complex Example: Copy to clipboard without displaying input), or for faster results, simply replace your copyUrl(text) with copyTextToClipboard(text) and its content like so:

export default {
  name: 'HelloWorld',
  props: {
    msg: String,
  },
  methods: {
    copyText(text) {
      var textArea = document.createElement('textarea');

      textArea.style.position = 'fixed';
      textArea.style.top = 0;
      textArea.style.left = 0;

      textArea.style.width = '2em';
      textArea.style.height = '2em';

      textArea.style.padding = 0;

      textArea.style.border = 'none';
      textArea.style.outline = 'none';
      textArea.style.boxShadow = 'none';

      textArea.style.background = 'transparent';

      textArea.value = text;

      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();

      try {
        var successful = document.execCommand('copy');
        var msg = successful ? 'successful' : 'unsuccessful';
        console.log('Copying text command was '   msg);
      } catch (err) {
        console.log('Oops, unable to copy');
      }

      document.body.removeChild(textArea);
    },
  },
};

LIVE DEMO

CodePudding user response:

No need to pass data to the function, try something like below

methods: {
  copyUrl() {
   var cpLink = window.location.href;
   cpLink.select();
   try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copy command was '   msg);
   } catch (err) {
     console.log('Oops, unable to copy');
   }
   event.preventDefault; 
 }
}
  • Related