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.
Assuming you already have a Vue project set up, install vue-clipboard2 as with any other Yarn or NPM package.
Now, as always, enable the plugin in your main app file.
Now, it’s just a matter of adding a v-clipboard:copy directive to your button.
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.
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!
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!