Member-only story
How to copy to clipboard with VueJS
All of my stories are free. If you aren’t a member, you can read it here.
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');