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 HTML element on button click to the clipboard.

1. Download Clipboard.js

  • Download package from GitHub and extract 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>


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>

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

Enter text in the first textarea and click the button.

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.

Related Posts