1 下载

  1. npm install vue-clipboard2

2 clipboard2是什么

vue-clipboard2是前端能够调用剪切板的一个插件。

3 在main.js配置

  1. // 剪切板
  2. import './plugins/clipboard2'

4 在src/plugins/clipboard2.js文件配置

  1. import Vue from 'vue'
  2. import VueClipboard from 'vue-clipboard2'
  3. Vue.use(VueClipboard)

5 示例

  1. <div id="app"></div>
  2. <template id="t">
  3. <div class="container">
  4. <input type="text" v-model="message">
  5. <button type="button"
  6. v-clipboard:copy="message"
  7. v-clipboard:success="onCopy"
  8. v-clipboard:error="onError">Copy!</button>
  9. </div>
  10. </template>
  11. <script>
  12. new Vue({
  13. el: '#app',
  14. template: '#t',
  15. data: function () {
  16. return {
  17. message: 'Copy These Text'
  18. }
  19. },
  20. methods: {
  21. onCopy: function (e) {
  22. alert('You just copied: ' + e.text)
  23. },
  24. onError: function (e) {
  25. alert('Failed to copy texts')
  26. }
  27. }
  28. })
  29. </script>

31578-a108f6e282b74d18.webp
第二种方式

<button @click="seccendCopy">第二种方式复制</button>
seccendCopy() {
      this.$copyText(this.value).then(
        function(e) {
          console.log("copy arguments e:", e);
          alert("复制成功!");
        },
        function(e) {
          console.log("copy arguments e:", e);
          alert("复制失败!");
        }
      );
}