Copy text to Clipboard using vue-clipboard2 – Vue.js

Copying the selected text from the webpage or input HTML element is easy with the keyboard shortcut CTRL+C and context menu.

To make it little easier for the user you can add a button.

For copy text to the clipboard in Vue.js, you can use the vue-clipboard2 package.

In this tutorial, I show how you can copy text from an HTML element on a button click to the clipboard.

Copy text to Clipboard using vue-clipboard2 – Vue.js


Contents

  1. Download Clipboard.js
  2. HTML
  3. Script
  4. Demo
  5. Conclusion

1. Download Clipboard.js

  • Download the package from GitHub and extract it in your project directory.
  • Include vue-clipboard.min.js script with vue.js in the <head> section.
<script src="vue.js"></script>
<script src="vue-clipboard2-master/dist/vue-clipboard.min.js"></script>

2. HTML

Create two <textarea> and a button.

The first textarea for inputting some text and the second textarea to display the copied text when a button gets clicked.

In the button define 3 attributes –

  • v-clipboard:copy – Here, passed the model name message from where to copy text.
  • v-clipboard:success – Pass method name onCopy. This called when text copied successfully.
  • v-clipboard:error – Pass method name onError. This called when it failed to copy text.

Completed Code

<div id="app">
 <textarea v-model='message'></textarea>
 <button type="button"
 v-clipboard:copy="message"
 v-clipboard:success="onCopy"
 v-clipboard:error="onError">Copy!</button>

 <br/>
 Copied Text: <br/><textarea v-model='copiedText'></textarea>
</div>

3. Script

Create two data variables – message, and copiedText.

Define two methods –

  • onCopy – Called when copy text to the clipboard. Assign e.text to this.copiedText.
  • onError – Called when failed to copy text.

Completed Code

new Vue({
  el: '#app',
  data:{
    message: '',
    copiedText: ''
  },
  methods: {
    onCopy: function (e) {
       this.copiedText = e.text;
    },
    onError: function (e) {
       console.log('Failed to copy texts')
    }
  }
})

4. Demo

View Demo


5. Conclusion

With vue-clipboard2.js package you can easily copy text to clipboard on the button click. It works the same as copying text by pressing CTRL+C from the keyboard.

If you found this tutorial helpful then don't forget to share.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.

1 thought on “Copy text to Clipboard using vue-clipboard2 – Vue.js”

Leave a Comment