1. 安装并引入
npm install vue-clipboard2 --save
// 全局引入main.js import VueClipboard from 'vue-clipboard2' Vue.use(VueClipboard)
2. 使用
方法一
<template> <div> <el-button v-clipboard:copy="copyData" v-clipboard:success="onCopy" v-clipboard:error="onError"> 复制基本类型 </el-button> <el-button v-clipboard:copy="copyJson" v-clipboard:success="onCopy" v-clipboard:error="onError"> 复制引用类型 </el-button> </div> </template> <script> export default { data() { return { copyData:'Hello World', copyJson:'', copyArr:[ { province:'江苏', city:'南京', },{ province:'湖北', city:'武汉', } ] }; }, methods: { // 复制成功时的回调函数 onCopy (e) { this.$message.success("内容已复制到剪切板") }, // 复制失败时的回调函数 onError (e) { this.$message.error("抱歉,复制失败!") }, // 将引用数据类型转换为json字符串 formatData(){ this.copyArr.forEach((item)=>{ let jsonString = JSON.stringify(item) this.copyJson += jsonString + '\n' }) } }, mounted() { this.formatData() }, }; </script>
方法二
<template> <div> <el-button @click="doCopy">复制</el-button> </div> </template> <script> export default { data() { return { copyData:'Hello World', }; }, methods: { doCopy() { this.$copyText(this.copyData).then( (e) => { this.$message.success("内容已复制到剪切板"); console.log(e) // {action: "copy", text: "Hello World", trigger: button, clearSelection: ƒ} }, (e)=> { this.$message.error("抱歉,复制失败!") }) } }, }; </script>
3. 效果
copyData: Hello World copyJson: {"province":"江苏","city":"南京"} {"province":"湖北","city":"武汉"}