实现按键就指定内容复制到设备的剪贴版,这里是复制快递单号
html
<div slot="footer" v-if="express.number" style="padding: 20px 0"> <span style="float: left;line-height: 30px">物流信息:{{express.company}}|{{express.number}}</span> <span class="req-feedback"> <van-button class="bt-check bt-bright" @click="copyNumber"> 复制快递单号 </van-button> </span> </div>
js
import {handleClipboard} from '../../assets/js/clipboard'
copyNumber () { // 物流单号复制 handleClipboard(this.express.number, event, () => { alert('单号已经复制在剪贴版') }, () => { alert('单号复制失败!') }) },
安装依赖:
"clipboard": "^2.0.4",
封装好的clipboard.js 放在了assets/js/clipboard.js
import Vue from 'vue' import Clipboard from 'clipboard' function clipboardSuccess () { Vue.prototype.$message({ message: '复制成功', type: 'success', duration: 1500 }) } function clipboardError () { Vue.prototype.$message({ message: '复制失败', type: 'error' }) } export function handleClipboard (text, event, onSuccess, onError) { event = event || {} const clipboard = new Clipboard(event.target, { text: () => text }) clipboard.on('success', () => { onSuccess ? onSuccess() : clipboardSuccess() clipboard.off('error') clipboard.off('success') clipboard.destroy() }) clipboard.on('error', () => { onError ? onError() : clipboardError() clipboard.off('error') clipboard.off('success') clipboard.destroy() }) clipboard.onClick(event) }