Js Vue 一键复制文本内容 - clipboard.js(兼容谷歌等主流浏览器)- 附完整示例
前端 vue js 一键复制文本内容 - clipboard.js(兼容谷歌等主流浏览器)
·
clipboard.js:将文本复制到剪贴板应该不难。它不需要几十个步骤来配置,也不需要数百个KB来加载。但最重要的是,它不应该依赖于Flash或任何臃肿的框架。
这就是clipboard.js存在的原因
目录
官方文档:clipboard.js — Copy to clipboard without Flash
浏览器兼容
效果
一、准备工作
1、安装依赖包
npm install clipboard --save
2、示例版本
"clipboard": "^2.0.8"
二、使用步骤
1、在index.html文件中引入依赖包
代码如下(示例):
<script type=“text/javascript” src="dist/clipboard.min.js"></script>
2、单文件使用
代码如下(示例):
import ClipboardJS from 'clipboard';
const clipboard = new ClipboardJS('.btn');
clipboard.on('success', function(e) {
console.log(e);
console.info('Text:', e.text);
message.info('复制成功');
e.clearSelection();
});
clipboard.on('error', function(e) {
if(!e.text) message.error('暂无可复制的内容')
});
三、完整示例
index.html
<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>XXX</title>
<script type=“text/javascript” src="dist/clipboard.min.js"></script>
</head>
<body>
<div id="app"></div>
</html>
Clipboard.vue
<template>
<a-tooltip>
<template #title>点击复制</template>
<span style="margin: 5px 8px;">
<span class="copy" style="cursor: pointer;" :data-clipboard-text="coord">{{coord}}</span>
</span>
</a-tooltip>
</template>
<script lang="ts" setup>
import { ref, onBeforeUnmount } from 'vue';
import { message } from 'ant-design-vue';
import ClipboardJS from 'clipboard';
const coord = ref('这里是可以点击复制的文本内容哦');
const clipboard = new ClipboardJS('.copy');
clipboard.on('success', function(e) {
console.log(e);
console.info('Text:', e.text);
message.info('复制成功');
e.clearSelection();
});
clipboard.on('error', function(e) {
if(!e.text) message.error('暂无可复制的内容')
});
onBeforeUnmount(() => {
clipboard.destroy();
})
</script>
欢迎扫描下方二维码关注VX公众号
更多推荐
已为社区贡献8条内容
所有评论(0)