Copy url to clipboard via button click in a vuejs component
You can use navigator object with clipboard in javascript.
Note: navigator.clipboard.writeText is asynchronous.
methods: {
async copyURL(mytext) {
try {
await navigator.clipboard.writeText(mytext);
alert('Copied');
} catch($e) {
alert('Cannot copy');
}
}
}
Most modern web explorers (2021) let you use this: navigator.clipboard.writeText("yourText");
Just in case you can also do this:
const clipboardData =
event.clipboardData ||
window.clipboardData ||
event.originalEvent?.clipboardData ||
navigator.clipboard;
clipboardData.writeText(message);
If you need to use vuejs ref
add it as attribute
<a :href="link_url" class="text-dark" target="_blank" rel="noopener noreferrer" ref="mylink">
{{ link_name }}
</a>
and use it in your method in the following way:
methods: {
copyURL() {
var Url = this.$refs.mylink;
Url.innerHTML = window.location.href;
console.log(Url.innerHTML)
Url.select();
document.execCommand("copy");
}
}
However, you should take a look to this link for a better cross-browsing solution. In this case you don't need the ref
attribute.
This is the solution in the link adapted to your case:
methods: {
copyUrl() {
const el = document.createElement('textarea');
el.value = this.link_url;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
const selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
el.select();
document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
}
}