js - 复制功能
tools - 复制功能
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>复制</title>
</head>
<body>
<input id="demoInput" value="copyValue" />
<input type="button" onclick="copyValue()" value='copy' />
<script>
function copyValue(){
const input = document.querySelector('#demoInput');
input.select();
if (document.execCommand('copy')) {
document.execCommand('copy');
alert('复制成功');
}
}
function setCopyValue(){
const text = document.createElement('textarea');
text.value = value;
document.body.appendChild(text);
text.select();
if (document.execCommand('copy')) {
document.execCommand('copy');
alert('复制成功');
}
text.remove()
}
</script>
</body>
</html>
vue
// /utils/clipboard
import Vue from 'vue'
import Clipboard from 'clipboard'
function clipboardSuccess() {
Vue.prototype.$message({
message: 'Copy successfully',
type: 'success',
duration: 1500
})
}
function clipboardError() {
Vue.prototype.$message({
message: 'Copy failed',
type: 'error'
})
}
export default function handleClipboard(text, event) {
const clipboard = new Clipboard(event.target, {
text: () => text
})
clipboard.on('success', () => {
clipboardSuccess()
clipboard.destroy()
})
clipboard.on('error', () => {
clipboardError()
clipboard.destroy()
})
clipboard.onClick(event)
}
// /utils/copyMixin
import clipboard from '@/utils/clipboard'
export default {
methods: {
handleClipboard(text, event) {
clipboard(text, event)
}
}
}
// 使用页面
<template>
<b @click="handleClipboard('复制复制复制',$event)">复制</b>
</template>
<script>
import copyMixin from '@/utils/copyMixin'
export default {
mixins:[copyMixin],
}
</script>
Lee2