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

新手上路,请多包涵

我想将这个 for-loop 的内容复制到剪贴板:

 <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>

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

   handleCopy() {
     this.$refs.text.select();
     document.execCommand('copy');
    }

但这导致:

 Uncaught TypeError: this.$refs.text.select is not a function

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

PS 我尝试了一些 JS 特定的建议答案,比如 这样,但出现错误:

 Uncaught TypeError: Failed to execute 'selectNode' on 'Range': parameter 1 is not of type 'Node'.

原文由 qliq 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 568
2 个回答

基于 这个 答案,这里有一个选择 HTMLElement 的文本的函数:

 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);
  }
}

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

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

原文由 user5734311 发布,翻译遵循 CC BY-SA 4.0 许可协议

你可以在 npm:vue-clipboard 上使用 vue 插件

让我们首先制作要复制的 html 数据。之后我们可以使用npm插件来复制html数据

new Vue({
    el: '#app',
    data: {
        HTMLcontent:'',
        resultNames:["John","Steward","Rock"]
    },
    created() {
    },
    methods:{
        makeData(){
            var self = this;
            for(var i = 0; i < self.resultNames.length; i++){
                self.HTMLcontent += '<p>'+self.resultNames[i]+'</p>';
            }
        },
        copyData(){
            this.makeData();
            console.log(this.HTMLcontent);
        }
    }
});

然后安装一个vue-plugin

 npm install --save v-clipboard
import Clipboard from 'v-clipboard'
Vue.use(Clipboard)

之后对 copyData 函数进行如下更改

copyData(){
    this.makeData();
    this.$clipboard(this.invite_code);
    alert("Copied to clipboard");
}

希望能解决您的疑问

原文由 Ankush Sood 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题