clipboard + element-ui +vue 實現復制粘貼功能與提示


結合 clipboard.js 實現復制、粘貼功能

剪切功能參考官方文檔,個人認為用不太上(有富文本編輯器的時候可能才用得上,也或許不需要自己實現)

想要知道怎么使用,優先參考官方文檔(如何指定要復制的數據,如何復制指定的數據...)

  • 這篇博客主要是介紹如何實現復制功能並搭配上友好的交互提示(見下方的 demo 圖)

一般也就兩種操作情況

  • 1.復制指定元素的內容
    • data-clipboard-action="copy"(復制)
    • data-clipboard-target="#bar"(復制 id 為 bar 的元素的內容)
  • 2.點擊按鈕直接復制設定的內容
    • data-clipboard-text="diyContent"(復制到剪切板的內容為 diyContent)

demo 效果

申明

clipboard.js 官方文檔:clipboard.js

本博客 demo 采用的是 vue + element-ui + clipboard.js 實現

  • 官網上的提示效果用的是 GitHub's Primer (具體什么個操作還不太懂,沒去了解過)
  • 頁面上的復制成功提示效果調用的是 element-ui 的 Notification 通知 組件

環境配置

安裝 clipboard.js:npm install clipboard --save

安裝 element-ui...

步驟分析

// 0.復制選項 html 准備(參考官方文檔了解配置項)
    <p>原樣復制指定文本框內容</p>
    <div class="row">
      <textarea id="bar">Mussum ipsum cacilds...</textarea>
      <el-button
        class="copyBtn"
        data-clipboard-action="copy"
        data-clipboard-target="#bar"
        icon="el-icon-copy-document"
      >Copy</el-button>
    </div>
    
    <p>點擊復制自定義內容到剪切板</p>
    <div class="row">
      <el-button
        class="copyBtn"
        data-test="test..."
        :data-clipboard-text="diyContent"
        icon="el-icon-copy-document"
      >Copy</el-button>
    </div>

// 1.需要用到的地方引入 Clipboard
import Clipboard from 'clipboard'

// 2.用觸發操作對象實例化一個 clipboard 對象
var clipboard = new Clipboard(".copyBtn");

// 3.為其指定操作成功回調函數
var that = this
clipboard.on("success", function (e) {
    console.info("Action:", e.action);
    console.info("Text:", e.text);
    console.info("Trigger:", e.trigger);

    // 清除選中狀態
    e.clearSelection();

    that.$notify({
        title: '成功',
        message: '恭喜您復制成功,趕快去粘貼吧~',
        type: 'success',
        showClose: false
    });
});

// 4.為其指定操作失敗回調函數
clipboard.on("error", function (e) {
    console.error("Action:", e.action);
    console.error("Trigger:", e.trigger);

    that.$notify.error({
        title: '失敗',
        message: '操作失敗,請重試!',
        showClose: false
    });
});

demo 代碼實現

結構不是很好,但重在實現

src\App.vue

<template>
  <div id="app">
    <HelloWorld />
    <tableDataCopyDemo />
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'
import tableDataCopyDemo from './components/tableDataCopyDemo.vue'

export default {
  name: 'App',
  components: {
    HelloWorld,
    tableDataCopyDemo
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

src\components\HelloWorld.vue

<template>
  <div class="hello">
    <p>原樣復制指定文本框內容</p>
    <div class="row">
      <textarea id="bar">Mussum ipsum cacilds...</textarea>
      <el-button
        class="copyBtn"
        data-clipboard-action="copy"
        data-clipboard-target="#bar"
        icon="el-icon-copy-document"
      >Copy</el-button>
    </div>
    
    <p>點擊復制自定義內容到剪切板</p>
    <div class="row">
      <el-button
        class="copyBtn"
        data-test="test..."
        :data-clipboard-text="diyContent"
        icon="el-icon-copy-document"
      >Copy</el-button>
    </div>
  </div>
</template>

<script>
import Clipboard from "clipboard";
export default {
  name: "HelloWorld",
  data() {
    return {
      clipboard: null,
      diyContent: '這是我自定義的拷貝內容!'
    };
  },
  mounted() {
    /*
    // 寫法 1
    var that = this
    var clipboard = new Clipboard(".btn");
    clipboard.on("success", function (e) {
      console.info("Action:", e.action);
      console.info("Text:", e.text);
      console.info("Trigger:", e.trigger);

      // 清除選中狀態
      e.clearSelection();

      that.$notify({
        title: '成功',
        message: '恭喜您復制成功,趕快去粘貼吧~',
        type: 'success',
        showClose: false
      });
    });

    clipboard.on("error", function (e) {
      console.error("Action:", e.action);
      console.error("Trigger:", e.trigger);

      that.$notify.error({
        title: '失敗',
        message: '不支持復制哦!',
        showClose: false
      });
    });
    */
    this.clipboard = new Clipboard(".copyBtn");
    this.clipboard.on("success", this.successFunc)
    this.clipboard.on("error", this.errorFunc)
  },
  methods: {
    successFunc (e) {
      console.info("Action:", e.action);
      console.info("Text:", e.text);
      console.info("Trigger:", e.trigger);
      // 可以取到目標元素上的自定義屬性(可以據此再做一些處理)
      e.trigger.dataset.test && console.log(e.trigger.dataset.test)
      // 清除選中狀態
      e.clearSelection();

      this.$notify({
        title: '成功',
        message: '恭喜您復制成功,趕快去粘貼吧~',
        type: 'success',
        showClose: false
      });
    },
    errorFunc (e) {
      console.error("Action:", e.action);
      console.error("Trigger:", e.trigger);

      this.$notify.error({
        title: '失敗',
        message: '操作失敗,請重試!',
        showClose: false
      });
    }
  },
  beforeDestroy() {
    // 釋放內存
    this.clipboardclipboard.off("error");
    this.clipboardclipboard.off("success");
    this.clipboardclipboard.destroy();

  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.hello{
  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-direction: column;
}
#bar{
  margin-right: 15px;
}
.row{
  display: flex;
  justify-content: center;
}
</style>

src\components\tableDataCopyDemo.vue

<template>
    <div style="margin-right: auto;margin-left: auto;width: 800px">
      <p>復制表格數據,自定義組合</p>
      <el-table :data="list">
        <el-table-column label="雲盤鏈接" prop="url"></el-table-column>
        <el-table-column label="提取碼" prop="code"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click="copyLink(scope.row)" class="tag">復制</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
</template>

<script>
import Clipboard from 'clipboard'
export default {
  name: 'ClipboardTest',
  data () {
    return {
      list: [
        {'url': 'https://www.baidu.com/1', 'code': '1234'},
        {'url': 'https://www.baidu.com/2', 'code': '7777'},
        {'url': 'https://www.baidu.com/3', 'code': '9999'}
      ]
    }
  },
  methods: {
    copyLink (data) {
      console.log(1)
      let clipboard = new Clipboard('.tag', {
        text: function () {
          return `雲盤鏈接:${data.url} 提取碼:${data.code}`
        }
      })
      clipboard.on('success', e => {
        console.info("Action:", e.action);
        console.info("Text:", e.text);
        console.info("Trigger:", e.trigger);
        // this.$message({message: '復制成功', showClose: true, type: 'success'})
        
        this.$notify({
          title: '成功',
          message: '恭喜您復制成功,趕快去粘貼吧~',
          type: 'success',
          showClose: false
        });
        // 釋放內存
        clipboard.destroy()
      })
      clipboard.on('error', e => {
        console.error("Action:", e.action);
        console.error("Trigger:", e.trigger);
        // this.$message({message: '復制失敗,', showClose: true, type: 'error'})
        this.$notify.error({
          title: '失敗',
          message: '操作失敗,請重試!',
          showClose: false
        });
        clipboard.destroy()
      })
    }
  }
}
</script>

<style scoped>

</style>

demo 地址

(如果幫到你了,記得幫我點個 star,非常感謝~)

原生 JS API 了解

放個鏈接在這里,實在有需要再去了解

(監聽下列事件,再結合 paste 中的案例,即可在復制時、剪切時、粘貼時給選中內容做處理)

亦可結合點擊復制功能做個案例

contenteditable="true" html 標簽屬性,可以讓元素變得像輸入框一樣可編輯,具體騷操作再看吧)

本文參考文檔:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM