Copying Text With vue-clipboard2

Joshua Bemenderfer

Sometimes it’s really convenient to have a nice little “copy” button next to a tidbit of information in your web app. No big deal, just a little button right? Well, it turns out that’s a bit more difficult than one might expect. Copying text requires either creating or accessing an input element, setting the selection, and executing the copy command. To make things worse, it’s only supported in recent browsers. The most common way around this is to use Clipboard.js, a small library that does this for you. But its API lends itself more to Vanilla JS than Vue.js. Thankfully, vue-clipboard2 exists to wrap Clipboard.js and make it nice and simple to use.

This will be a nice and short article since vue-clipboard2 has an incredibly simple, no-nonsense API.

Installation

Assuming you already have a Vue project set up, install vue-clipboard2 as with any other Yarn or NPM package.

# Yarn
$ yarn add vue-clipboard2
# NPM
$ npm install vue-clipboard2 --save

Now, as always, enable the plugin in your main app file.

src/main.js

import Vue from 'vue';
import VueClipboard from 'vue-clipboard2'
import App from 'App.vue';

Vue.use(VueClipboard);

new Vue({
  el: '#app',
  render: h => h(App)
});

Usage

Now, it’s just a matter of adding a v-clipboard:copy directive to your button.

<template>
  <div>
    <p>Here, copy this thing: </p>
    <button v-clipboard:copy="thingToCopy"></button>
  </div>
</template>

<script>
export default {
  data: () => ({
    thingToCopy: `A string that's not all that long or important. Sorry to disappoint.`
  })
}
</script>

Of course, you want to be able to show feedback to your users when the copy succeeds or fails (especially since older browsers don’t work with this method,) so you should probably show a message when the copy succeeds or fails. This can be done with the v-clipboard:success and v-clipboard:error directives.

<template>
  <div>
    <p>Here, copy this thing: </p>
    <button
      v-clipboard:copy="thingToCopy"
      v-clipboard:success="handleCopyStatus(true)"
      v-clipboard:error="handleCopyStatus(false)"
    >
      Copy the thing!
    </button>
    <p v-if="copySucceeded === true">Copied!</p>
    <p v-if="copySucceeded === false">Press CTRL+C to copy.</p>
  </div>
</template>

<script>
export default {
  data: () => ({
    copySucceeded: null
    thingToCopy: `A string that's not all that long or important. Sorry to disappoint.`
  }),

  methods: {
    handleCopyStatus(status) {
      this.copySucceeded = status
    }
  }
}
</script>

And there you have it! Really simple copy-pasting for your Vue.js apps when you just can’t be bothered to implement it yourself. Enjoy!

✖ Clear

🕵 Search Results

🔎 Searching...