clipboard.js
是一款使用简单的粘贴复制插件,它不依赖于Flash或其他框架,在github
拥有3万多颗星可见其优秀程度,我们将介绍在umd
和vue
环境下如何使用它。
https://github.com/zenorocha/clipboard.js
npm install clipboard --save
如果你不想通过npm命令安装,也可以直接下载文件
下载 clipboard.js
//方法一:
<script src="https://www.itxst.com/package/clipboardjs/clipboard.min.js"></script>
//方法二:
import Clipboard from "clipboard"
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>clipboard例子</title>
<script src="https://www.itxst.com/package/clipboardjs/clipboard.min.js"></script>
</head>
<body style="padding:10px;">
<input id="foo" value="https://www.itxst.com"/>
<!-- Trigger -->
<input class="btn" id="btn" data-clipboard-target="#foo" type="button" value="复制">
<script>
//初始化对象
var clipboard = new ClipboardJS('.btn');
clipboard.on('success', function (e) {
console.info('Action:', e.action);
console.info('Text:', e.text);
console.info('Trigger:', e.trigger);
//注销对象
e.clearSelection();
document.getElementById("btn").value="复制成功";
});
clipboard.on('error', function (e) {
console.error('Action:', e.action);
console.error('Trigger:', e.trigger);
document.getElementById("btn").value="复制失败";
});
</script>
</body>
</html>
<template>
<div class="itxst">
<div>
<input v-model="state.message" />
<input class="btn" @click="copy" type="button" value="复制" />
</div>
</div>
</template>
<script setup>
import { ref, reactive } from "vue";
import Clipboard from "clipboard";
const state = reactive({
message: "https://www.itxst.com",
});
//复制方法,本例子是vue3环境下,同样在vue2中也可以使用
const copy = () => {
let clipboard = new Clipboard(".itxst", {
text: () => {
//返回需要复制的字符串
return state.message;
},
});
clipboard.on("success", () => {
clipboard.destroy();
});
clipboard.on("error", () => {
clipboard.destroy();
});
};
</script>
<style scoped>
</style>