如何在 Vue.js 中将 InnerHtml 复制到剪贴板? [英] How to copy InnerHtml to clipboard in Vue.js?
问题描述
我想将此 for 循环的内容复制到剪贴板:
<div class="row" v-for="(name, index) in resultNames" :key="index" ><p>{{makeUrl(name)}} </p>
<button @click="handleCopy">复制到剪贴板</button>
我遵循了这个的答案并想出了这个方法:
handleCopy() {this.$refs.text.select();document.execCommand('copy');}
但这会导致:
未捕获的类型错误:this.$refs.text.select 不是函数
所以我不知道如何在不使用第三方 javascript 插件的情况下解决这个问题?
PS 我尝试了一些 JS 特定的建议答案,例如 这个,但得到错误:
未捕获的类型错误:无法在范围"上执行选择节点":参数 1 不是节点"类型.
基于 this 答案,这里有一个函数选择一个 HTMLElement
的文本:
selectText(element) {变量范围;如果(文档.选择){//IErange = document.body.createTextRange();range.moveToElementText(元素);范围.选择();} else if (window.getSelection) {range = document.createRange();range.selectNode(元素);window.getSelection().removeAllRanges();window.getSelection().addRange(range);}}
剩下要做的是 a) 传递元素 b) 调用复制命令:
this.selectText(this.$refs.text);//例如<div ref="文本">document.execCommand("复制");
I'd like to copy the content of this for-loop into clipboard:
<div ref="text" class="links">
<div class="row" v-for="(name, index) in resultNames" :key="index" >
<p>{{makeUrl(name)}} </p>
</div>
</div>
<button @click="handleCopy">Copy to Clipboard</button>
I followed this answer and came up with this method:
handleCopy() {
this.$refs.text.select();
document.execCommand('copy');
}
But this results in:
Uncaught TypeError: this.$refs.text.select is not a function
So I'm left clueless how can I solve this withouth using third party javascript plugins?
P.S. I tried some JS specific suggested answers, like this, but get error:
Uncaught TypeError: Failed to execute 'selectNode' on 'Range': parameter 1 is not of type 'Node'.
Based on this answer, here's a function to select an HTMLElement
's text:
selectText(element) {
var range;
if (document.selection) {
// IE
range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
range = document.createRange();
range.selectNode(element);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
}
}
What's left to do is to a) pass the element b) call the copy command:
this.selectText(this.$refs.text); // e.g. <div ref="text">
document.execCommand("copy");
这篇关于如何在 Vue.js 中将 InnerHtml 复制到剪贴板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!