The vue project implements copying content to the clipboard

The vue project implements copying content to the clipboard

Introduce two implementations of copying content to the clipboard in the vue project:
1. execCommand('Copy') method:

(function () {
      document.oncopy = function (e) {
            e.clipboardData.setData('text', '要复制的内容');
            e.preventDefault();
            document.oncopy = null;
      }
})('要复制的内容');
document.execCommand('Copy');

2. clipboardData.setData() method:
first determine whether clipboardData is supported, and then execute the copy operation through the setData method of clipboardData.

if (window.clipboardData) {
      window.clipboardData.setData('text', '要复制的内容');
}

The combination of the two methods can increase the compatibility of each browser:
insert image description here
(**Remarks: **These two methods can be realized in the PC browser of the window system, and it is also feasible to test in the Android mobile phone, but it is invalid in the IOS mobile phone. The IOS system computer has not been tested, and it is estimated that it will not work.)

3. Implementation of third-party plug-in vue-clipboard2:
Install vue-clipboard2:

npm install vue-clipboard2

Introduced in the main.js file:
Vue2 introduced:

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

vue3 introduction:

import { createApp } from 'vue'
import VueClipboard from 'vue-clipboard2'

const app = createApp(App)
app.use(VueClipboard)

use:

this.$copyText('要复制的内容').then(function (e) {
     console.log('【复制成功】', e)
  }, function (e) {
     console.log('【复制失败】', e)
})

**(**Remarks: The vue-clipboard2 method is effective in Android phones, PC browsers in window systems, and IOS mobile browsers, and IOS computers and tablets have not been tested)

There is a small problem: when the this.$copyText() method is triggered, if it is triggered by a click event, the copy will be successful. If it is automatically triggered by setTimeout delay, the copy will fail when the delay time is set to exceed 4 seconds. I don't know what the reason is, interested workers can study the source code, welcome to leave a message! ! ! ! ! ! !

If it is helpful to you, remember to like it (~~)

Guess you like

Origin blog.csdn.net/start_sea/article/details/121143340