如何在 Vue.js 中将 InnerHtml 复制到剪贴板?

qli*_*liq 3 javascript vue.js

我想将此 for 循环的内容复制到剪贴板:

<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> 
Run Code Online (Sandbox Code Playgroud)

我按照这个答案提出了这个方法:

  handleCopy() {
     this.$refs.text.select();
     document.execCommand('copy');
    }
Run Code Online (Sandbox Code Playgroud)

但这导致:

Uncaught TypeError: this.$refs.text.select is not a function
Run Code Online (Sandbox Code Playgroud)

所以我不知道如何在不使用第三方 javascript 插件的情况下解决这个问题?

PS我尝试了一些 JS 特定的建议答案,像这样,但得到错误:

Uncaught TypeError: Failed to execute 'selectNode' on 'Range': parameter 1 is not of type 'Node'.
Run Code Online (Sandbox Code Playgroud)

Chr*_*s G 9

基于答案,这是一个选择HTMLElement's 文本的函数:

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

剩下要做的是 a) 传递元素 b) 调用复制命令:

this.selectText(this.$refs.text); // e.g. <div ref="text">
document.execCommand("copy");
Run Code Online (Sandbox Code Playgroud)