浏览器复制文本内容到浏览器,clipboard插件解决线上的兼容性

Posted 勇敢*牛牛

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了浏览器复制文本内容到浏览器,clipboard插件解决线上的兼容性相关的知识,希望对你有一定的参考价值。

本地

这样在本地跑一般是没有问题的

 copy()
    try 
        navigator.clipboard.writeText("我爱你").then(()=>
          this.$message(type:"success",message:"已经复制到粘切板",center:true) 
        ,()=>
        this.$message(type:"error",message:"请使用高版本浏览器,才能执行粘切操作",center:true) 
        )
     catch (error) 
        this.$message(type:"error",message:error,center:true) 
    
  

线上

线上环境这一段代码就会报错;
Cannot read properties of undefined (reading 'writeText')

可以使用插件:clipboar
yarn add clipboar
import Clipboard from 'clipboard'
在vue中这样使用一下:

有数据源为:
fromtData = '我\\n爱\\n你'

使用之前,将需要的数据绑定到这个组件上面

<el-button type="success" @click="copy" class="report-import-button"  :data-clipboard-text='fromtData'>将内容赋值到粘切板</el-button>

使用ing
import Clipboard from 'clipboard'
//绑定数据来源,创建实例挂载到某个dom上面
const myClip = new Clipboard('.report-import-button')
//copy到粘切板
copy()
	
	myClip.on('success', (e: any) => 
		this.$message(type:"success",message:"已经复制到粘切板",center:true) 
		myClip.destroy()
		e.clearSelection()
	)
	myClip.on('error', () => 
		this.$message(type:"error",message:"请使用高版本浏览器,才能执行粘切操作",center:true) 
	)


以上是关于浏览器复制文本内容到浏览器,clipboard插件解决线上的兼容性的主要内容,如果未能解决你的问题,请参考以下文章

vue项目中做点击按钮复制文本框内容

js插件实现一键复制功能

js实现复制隐藏域的内容 —— clipboard.js

clipboard插件的使用

浏览器点击复制粘贴到剪切板的解决

react---之复制输入框文本内容