Easy copy to clipboard with vue-clipboard2

Jean-Philippe Fong
VueJoy
Published in
2 min readJul 1, 2018
Photo by rawpixel on Unsplash

Copy to clipboard is a feature that can be useful to the users of your app and can be set up easily thanks to a simple module called vue-clipboard.

Let’s set up a quick example, straight from the documentation!

First, you can set up a Vue app quickly with the vue-cli.

Then, you just need to add vue-clipboard2 to your app. Let’s do this with yarn.

yarn add vue-clipboard2

After that, you need to import this module in your main.js file:

import VueClipboard from ‘vue-clipboard2’
Vue.use(VueClipboard)

We will modify our template to add an input text and a button to make our copy to clipboard:

<input type=”text” v-model=”message”>
<button type=”button”
v-clipboard:copy=”message”
v-clipboard:success=”onCopy”
v-clipboard:error=”onError”>Copy!</button>

We are using the module in the template. message is the name of the data that we want to copy, you can modify it by typing in the input.

If the copy is successful, we show an alert with the copied text in the onCopy method. On error, we tell the user that there was an error, with the onError:

 export default {
name: 'app',
data () {
return {
message: null
}
},
methods: {
onCopy: function (e) {
alert('You just copied: ' + e.text)
},
onError: function (e) {
alert('Failed to copy texts')
}
}
}

You can find the source code here.

And also, a live example here, thanks to Netlify!

VueJoy ebook is ready for preorder!

Learn VueJs with tutorial and examples.

Get new chapters as they’re completed and get updates!

Preorder now: http://www.vuejoy.com!

--

--