Vue-Click to copy content method - the use of clipboard

clipboard.js:

clipboard.js is a lightweight JavaScript plugin that implements the function of copying text to the clipboard. Through this plug-in, text content such as input boxes, text fields, and DIV elements can be copied to the clipboard.
clipboard.js supports mainstream browsers: chrome 42+; Firefox 41+; IE 9+; opera 29+; Safari 10+;

download

npm install clipboard --save

use

How to copy content from clipboard:

  • Copy target content from target
  • The content to be copied through function
  • Return the copied content through attributes

Import js file:

import Clipboard from 'clipboard';
new Clipboard('.btn')
  1. Scenario 1: Click to copy input box content: Insert image description here
    A very common use case is to copy content from another element. You can do this by adding a data-clipboard-target attribute to the target element.
    The value of this attribute is the selector that matches another element.
  • html:
在这里插入代码片
```<!-- Target -->
<input id="foo" value="复制文本">
<!-- Trigger -->
<button class="btn" data-clipboard-target="#foo">
    <img src="assets/clippy.svg" alt="Copy to clipboard">
</button>
  1. Scenario 2: Cutting text from another element
    You can define a data-clipboard-action attribute to indicate whether you want to copy or cut the content, and the default is copy.
    Insert image description here
  • html:
<!-- Target -->
<textarea id="bar">点击下面按钮复制文本.</textarea>

<!-- Trigger -->
<button class="btn" data-clipboard-action="cut" data-clipboard-target="#bar">
    Cut to clipboard
</button>

Note: The cut operation only takes effect on the or element

  • Scenario Three: Copying Text from Attributes
    You don't even need to copy content from another element. Just set a data-clipboard-text attribute for the target element
    Insert image description here

  • html:

<button class="btn" data-clipboard-text="这是复制文本">
    Copy to clipboard
</button>
  • Scenario 4: Want to display some user feedback after copying, or get the selected text after the user copies/cuts
    Insert image description here
  • HTML(pug format)
el-button(v-if='shopCode' type='text' @click='copyShopCode' size='mini' class='copy') 复制门店code
  • js
import Clipboard from 'clipboard';
....

    // 复制门店code函数
    copyShopCode() {
    
    
      const clipboard = new Clipboard('.copy', {
    
    
        // 点击copy按钮,直接通过text直接返回复印的内容
        text: () => this.baseInfo.shopCode,
      });
        // 通过传递DOM选择器,HTML元素或HTML元素列表实例化
      clipboard.on('success', (e) => {
    
    
        this.$message.success(`复制成功,内容为:${
      
      e.text}`);
        e.clearSelection();
          // 释放内存
        clipboard.destroy();
      });
      clipboard.on('error', () => {
    
    
          // 不支持复制
        this.$message.error('该浏览器不支持自动复制');
          // 释放内存
        clipboard.destroy();
      });
    },

Guess you like

Origin blog.csdn.net/khadijiah/article/details/107369726