In a previous tutorial, I described how to easily copy text to the clipboard with different options in JavaScript. Nowadays, you gotta work with some framework especially when working on SPA projects. Most of the time, the regular methods shouldn't be used as they go against the logic of the frameworks, and handling the clipboard with JavaScript using Vue.js is not the exception.
In this tutorial, I'll explain to you how to easily copy text to the clipboard in Vue.js 2.
1. Install Vue Clipboard 2
The Vue Clipboard 2 package offers Vue bindings for the known JS library clipboard.js that will allow you to copy text to the clipboard with pure JavaScript. To install this package in your project, run the following command in the terminal:
npm install --save vue-clipboard2
For more information about this package, visit the official repository at Github here.
2. Include Vue Clipboard
After installing the Vue Clipboard package in your project with the mentioned instruction, you may now include it in your application like this:
// main.js
import Vue from 'vue'
import VueClipboard from 'vue-clipboard2'
Vue.use(VueClipboard)
Or in case you are using Vue.js in the standalone version, you will need to reference the JS file manually like this:
<script src="vue.min.js"></script>
<!-- must place this line after vue.js -->
<script src="dist/vue-clipboard.min.js"></script>
After doing this you should be able now to use the library in your application.
3. Copying text to the clipboard in Vue
Everyone learns by example, so to understand how to copy text to the clipboard in Vue, you can do it like this.
Example to copy the text from an input
The following Vue.js component shows how to use the library to copy the text from an input using the Vue logic. In the markup, we have 2 elements, the text input, and a button. The button has attached 2 callbacks to 2 events that will be triggered respectively when the event happens. The copy attribute specifies the data that will be copied to the clipboard, in this case, the value of the message data property:
<template>
<div>
<input
type="text"
placeholder="Insert your YouTube URL here ..."
v-model="message"
/>
<button
type="button"
v-clipboard:copy="message"
v-clipboard:success="onCopy"
v-clipboard:error="onError"
>
Copy!
</button>
</div>
</template>
<script>
export default {
name: "YourComponentName",
data: function () {
return {
message: 'The text inside this text input will be copied to the clipboard'
}
},
methods: {
onCopy: function (e) {
alert('You just copied the following text to the clipboard: ' + e.text)
},
onError: function (e) {
alert('Failed to copy the text to the clipboard')
console.log(e);
}
}
};
</script>
Remember that there should be always interaction from the user in order to replace the context of the clipboard, as nobody wants to lost what they had in the clipboard because of an invasive action from a web application.
Happy coding ❤️!