How to copy to clipboard with VueJS
History lesson
First of all, I want to dive a bit into the history of copy to clipboard in browsers.
The ‘legacy’ API, which still works marvelously, but is technically obsolete, is document.execCommand('copy')
whatever is currently selected, will get copied to clipboard.
2 notes about document.execCommand('copy')
1. It must be the user doing the action, doing it from the console will not work.
2. It is still considered a good fallback, and there doesn’t seem to be a switchover date yet
Example:
Try it out here
A few things to take a note of, the flow is as follows; button click
> Set Focus on the $ref
(input) > onFocusEvent
> Select text > Copy to clipboard.
Minor note: This does not work with disabled
input, if you need similar use readonly
instead.
The new way of doing things
clipboard.writeText('Text to get copied');
This is the new supported API for copying and pasting things, and it has pretty broad support at the time of this writing.
But what about VueJS?!
I generally go with the ‘legacy’ api for copy pasting, as it has slightly different semantics and generally works better than the new API (in my opinion)
So basically, the idea is to create a readonly
input field, with a ref
and an on-focus
handler that selects what is in the input field.
Next to it will be a button with a single click
handler, that calls copy()
The copy
method focuses the input field, which will select the text (due to the on:focus
handler) and the document.exeCommand('copy');
will be executed.
You can see it in action here