vue或H5中使用复制粘贴
1.使用原生的方法,一般都是在浏览器上使用,所以兼容性不是很好
我是直接使用原生方法创建的input,你也可以直接在DOM上加input标签,然后去获取它的value值.
copyUrl(){ ? ?let url = 'https://blog.csdn.net/linfng023/article/details/101014133'; ? ?let domInput = document.createElement('input'); ? ?domInput.value = url; ? ?document.body.appendChild(domInput); ?// 添加input节点 ? ?domInput.select(); // 选择对象; ? ?document.execCommand("Copy"); // 执行浏览器复制命令 ? ?this.$toast({ ? ? ?message: `链接复制成功!`, ? ? ?duration: 2000 ? ?}); ? ?domInput.remove() },
2.使用插件的方式 clipboard.js ,使用步骤:
安装clipboard.js,可以使用npm安装(也可以cnpm)
npm install clipboard --save
引入clipboard.js,可以mian.js上直接引用(全局使用),也可以在你需要复制粘贴的组件上引用(局部使用)
import clipboard from 'clipboard'; //注册到vue原型上 Vue.prototype.clipboard = clipboard;
然后复制粘贴
<a class="copyClassUrl" data-clipboard-action="copy" data-clipboard-text="https://blog.csdn.net/linfng023/article/details/101014133" @click="copyLink">复制链接</a>
copyLink() { ? ? let clipboardUrl = new this.clipboard(".copyClassUrl"); ? ? clipboardUrl.on('success', function () { ? ? ? _this.$toast({ ? ? ? ? message: `链接复制成功!`, ? ? ? ? duration: 2000 ? ? ? }); ? ? }); ? ? clipboardUrl.on('error', function () { ? ? ? console.log(clipboardUrl) ? ? }); },
复制粘贴功能 :H5或vue或uniapp
1.原生的浏览器复制方式,一般都是在浏览器上使用
单独定义一个h5-copy.js文件。用于复用 复制粘贴功能
h5-copy.js
export default function h5Copy(content) { ? console.log(content); ? if (!document.queryCommandSupported('copy')) { ? ? // 不支持 ?? ?uni.showToast({ ?? ??? ?title:'您当前的应用环境不支持自动复制内容......', ?? ??? ?icon:'none' ?? ?}) ? ? return false ? } ?? ? let textarea = document.createElement("textarea") ? textarea.value = content ? textarea.readOnly = "readOnly" ? document.body.appendChild(textarea) ? textarea.select() // 选择对象 ? textarea.setSelectionRange(0, content.length) //复制的内容的范围? ? let result = document.execCommand("copy") // 执行浏览器复制命令 ? textarea.remove() ? return result ? }
然后在文件中使用
<template> <view> <button type="primary" size="mini" @click="copy">文字复制</button> </view> </template> <script> import h5Copy from '@/utils/h5-copy.js' export default { data() { return { }; }, methods:{ copy(){ // #ifdef H5 let res = h5Copy('传入要复制的内容') if (res) { uni.showToast({ title:'复制成功', icon:"success" }) //window.location.href = "weixin://"; } else { uni.showToast({ title:'复制失败', icon:"none" }) } // #endif // #ifdef APP-PLUS uni.setClipboardData({ data: '要复制的内容', success: () => { //复制成功之后的回调 do something here uni.showToast({ title: '复制成功' }) }, fail: () => { //复制失败之后的回调 do something here uni.showToast({ title: '复制失败', icon: "none" }) } }); // #endif } } } </script> <style lang="scss"></style>
如果要是在uniapp中使用app与h5 同时都实现复制粘贴功能的话:
H5可使用上述方式实现, app可以用 uniapp官网的复制粘贴的api接口以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
查看更多关于在vue或H5中如何使用复制粘贴功能的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did120996