对我不起作用,试试这个 -
<input type="hidden" id="testing-code" :value="testingCode">
copyTestingCode () {
let testingCodeToCopy = document.querySelector('#testing-code')
testingCodeToCopy.setAttribute('type','text')
testingCodeToCopy.select()
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
alert('Testing code was copied ' + msg);
} catch (err) {
alert('Oops,unable to copy');
}
/* unselect the range */
testingCodeToCopy.setAttribute('type','hidden')
window.getSelection().removeAllRanges()
},
https://codepen.io/PJCHENder/pen/jamJpj?editors=1010,请
,
大多数现代网络浏览器 (2021) 都允许您使用它:
navigator.clipboard.writeText("yourText");
以防万一您也可以这样做:
const clipboardData =
event.clipboardData ||
window.clipboardData ||
event.originalEvent?.clipboardData ||
navigator.clipboard;
clipboardData.writeText(message);
,
如果您需要使用vuejs ref
将其添加为属性
<a :href="link_url" class="text-dark" target="_blank" rel="noopener noreferrer" ref="mylink">
{{ link_name }}
</a>
,并通过以下方式在您的方法中使用它:
methods: {
copyURL() {
var Url = this.$refs.mylink;
Url.innerHTML = window.location.href;
console.log(Url.innerHTML)
Url.select();
document.execCommand("copy");
}
}
但是,您应该查看此link以获得更好的跨浏览解决方案。在这种情况下,您不需要ref
属性。
这是适合您情况的链接中的解决方案:
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);
}
}
}
本文链接:https://www.f2er.com/3150746.html