首页 > 解决方案 > 在 vue.js 中将表格复制到剪贴板

问题描述

我正在尝试将 div 元素复制到 vuejs 中的剪贴板。我已经通过搜索相关的解决方案并申请了。但不工作。我想将整个表格复制到剪贴板。提前致谢

 <button v-on:click = "copyToClipboard(select_txt)">Click To Copy</button>
                <table class="table table-sm" id="select_txt">
                    <tr>
                        <td>Name</td>
                        <td> abcd </td>
                    </tr>
                    <tr>
                        <td>Phone</td>
                        <td>124545</td>
                    </tr>
                </table>

方法

 methods:{
        copyToClipboard(containerid){
            var range = document.createRange();
            range.selectNode(containerid); 
            window.getSelection().removeAllRanges();
            window.getSelection().addRange(range);
            document.execCommand("copy");
            window.getSelection().removeAllRanges();
            alert("data copied");
        }
    },

标签: vue.jsvuejs2

解决方案


您在选择节点时做错了什么。

copyToClipboard(containerid){
            var range = document.createRange();
            let containerNode = document.getElementById(containerid); //// this part
            range.selectNode(containerNode); //// this part
            window.getSelection().removeAllRanges();
            window.getSelection().addRange(range);
            document.execCommand("copy");
            window.getSelection().removeAllRanges();
            alert("data copied");
        }

复制html代码

copyToClipboard(containerid) {
      let containerNode = document.getElementById(containerid);
      var textArea = document.createElement("textarea");
      textArea.style.position = "fixed";
      textArea.style.top = 0;
      textArea.style.left = 0;

      // Ensure it has a small width and height. Setting to 1px / 1em
      // doesn't work as this gives a negative w/h on some browsers.
      textArea.style.width = "2em";
      textArea.style.height = "2em";

      // We don't need padding, reducing the size if it does flash render.
      textArea.style.padding = 0;

      // Clean up any borders.
      textArea.style.border = "none";
      textArea.style.outline = "none";
      textArea.style.boxShadow = "none";

      // Avoid flash of white box if rendered for any reason.
      textArea.style.background = "transparent";

      textArea.value = containerNode.outerHTML;

      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      document.execCommand("copy");
      window.getSelection().removeAllRanges();
      document.body.removeChild(textArea);
      alert("data copied");
    }

推荐阅读