h5复制功能在uni-app里面遇见的坑
一开始封装的代码
copy(value) {
//提示模板
uni.showModal({
content: value, //模板中提示的内容
confirmText: '复制内容',
success: () => { //点击复制内容的后调函数
//uni.setClipboardData方法就是讲内容复制到粘贴板
// API `setClipboardData` is not yet implemented
//意思是H5端没有这个接口!!!
uni.setClipboardData({
data: value, //要被复制的内容
success: function() {
//重点~做笔记
//在success中加入uni.hideToast()可以解决
uni.hideToast({
title: '复制成功',
duration: 2000,
icon: 'none'
});
//以下就可自定义操作了~
},
fail: function(err) {
uni.showToast({
title: '复制失败',
duration: 2000,
icon: 'none'
});
}
});
}
});
}
后来发现uni-app编译成h5不支持
之后换的方法
第一种
uniapp在H5端不支持剪切板,这里通过clipboard实现(vue中也可使用此封装函数)
第一步:安装 npm i clipboard --save
第二步:封装复制函数
import Clipboard from 'clipboard'
export function handleClipboard (text, event, onSuccess, onError) {
event = event || {}
const clipboard = new Clipboard(event.target, {
text: () => text
})
clipboard.on('success', () => {
onSuccess()
clipboard.off('error')
clipboard.off('success')
clipboard.destroy()
})
clipboard.on('error', () => {
onError()
clipboard.off('error')
clipboard.off('success')
clipboard.destroy()
})
clipboard.onClick(event)
}
第三步:在需要使用的页面使用
<view class="btn2" @click="copy('需要复制的内容')">复制</view>
import {handleClipboard} from '../../utils/clipboard.js'
copy(data) {
// #ifdef H5
handleClipboard(data, event, () => {
uni.showToast({
icon: 'none',
title: '资源地址已复制成功'
})
}, () => {
uni.showToast({
icon: 'none',
title: '复制失败'
})
})
// #endif
},
第二中
copyText(val){
let result
// #ifndef H5
uni.setClipboardData({
data: val,
success() {
result = true
},
fail() {
result = false
}
});
// #endif
// #ifdef H5
let textarea = document.createElement("textarea")
textarea.value = val
textarea.readOnly = "readOnly"
document.body.appendChild(textarea)
textarea.select() // 选中文本内容
textarea.setSelectionRange(0, val.length)
result = document.execCommand("copy")
textarea.remove()
// #endif
return result
},