vue2实现复制,粘贴功能,使用vue-clipboard2插件

一、需求说明

在项目中 点击按钮 复制 某行文本是很常见的 应用场景,

在 Vue 项目中实现 复制功能 需要借助 vue-clipboard2 插件。

二、代码实现

1、安装 vue-clipboard2 依赖

( 出现错误的话,可以试试切换成淘宝镜像源

npm config set registry https://registry.npm.taobao.org

npm install --save vue-clipboard2

2、在 main.js 文件中全局引入插件

示例代码如下:

import Vue from 'vue'

import VueClipBoard from 'vue-clipboard2'

Vue.use(VueClipBoard)

new Vue({

render: h => h(App)

}).$mount('#app')

3、案例

在组件中有两种方法可以实现复制功能。

方法一 :

使用 vue-clipboard2 提供的 指令

直接将变量内容复制至剪切板,暂时没有找到处理数据后再复制的方式

<template>

<div class="yeluosen">

<input type="text" v-model="message">

<el-button

icon="el-icon-share"

size="mini"

style="font-size: 16px;padding: 4px 8px;"

title="共享"

v-clipboard:copy="scope.row.url"

v-clipboard:success="onCopy"

v-clipboard:error="onError"

@click="share(scope.row.url)"></el-button>

</div>

</template>

复制时,通过 v-clipboard: copy 复制输入的内容 :

// 复制成功 or 失败(提示信息!!!)

onCopy: function (e) {

console.log('复制成功!', e)

},

onError: function (e) {

console.log('复制失败!', e)

}

方法二:

使用 vue-clipboard2 全局绑定的 $copyText 事件方法

复制动作使用的是 Vue 响应函数方式,这就为复制前控制数据提供了可能!

// 点击事件

share(val) {

this.handleData(val)

this.$copyText(this.message).then(function (e) {

alert('Copied')

}, function (e) {

alert('Can not copy')

})

},

// 数据处理

handleData(val){

this.message = this.message + ' ' + val

}

<template>

<div>

<el-button

type="success"

size="small"

style="margin-left: 10px"

@click="onCopy"

>复制</el-button

>

</div>

</template>

<script>

export default {

data() {

return {

text: "这是一段复制的文本",

};

},

methods: {

onCopy() {

this.$copyText(this.pathText).then(

e=>{

console.log('复制成功:', e);

},

e=>{

console.log('复制失败:', e);

}

)

}

}

};

</script>

三、项目所用

实现选中并且复制成功后带有提示信息的效果 :

<template>

<div>

<el-input ref="addressInput" v-model="address" :readonly="true">

<template slot="prepend"> 反馈地址 </template>

</el-input>

<el-button @click="copyLink(address)">复制链接</el-button>

</div>

</template>

<script>

export default {

data() {

return {

address: "https://www.baidu.com/", // 地址信息

};

},

methods: {

// 判断是否是 IE 浏览器

isIE() {

if (window.ActiveXObject || "ActiveXObject" in window) {

return true;

} else {

return false;

}

},

// 拷贝地址

copyLink(url) {

if (this.isIE()) {

this.$copyText(url);

this.$refs.addressInput.select(); // 实现选中效果

this.$message.success("复制成功!");

} else {

this.$copyText(url)

.then((res) => {

this.$refs.addressInput.select(); // 实现选中效果

this.$message.success("复制成功!");

})

.catch((err) => {

this.$message.error("该浏览器不支持自动复制, 请手动复制");

});

}

},

},

};

</script>

<style lang="scss" scoped></style>

优化一下,我想要复制一个对象,需要做转义,像这样

javascript 复制代码
<el-dialog title="提示" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
  
      <span slot="footer" class="dialog-footer">
        <span>{{ form.address }}</span>
        <span>{{ form.name }}</span>
        <span>{{ form.password }}</span>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
        <el-button type="primary" @click="share(form)">复制</el-button>
      </span>
    </el-dialog>
javascript 复制代码
data(){
return{
 form: {
        address: "https://www.baidu.com/", // 地址信息
        name: "张三",
        password: "123",
      },
}
}
javascript 复制代码
 share(url) {
      if (this.isIE()) {

        this.$copyText(this.form.password);
        // this.$refs.addressInput.select(); // 实现选中效果
        this.$message.success("复制成功!");
      } else {
            //此处做转义,并且使用JSON.stringify转一下

        let obj = {
          '地址': this.form.address,
          '用户名': this.form.name,
          '密码': this.form.password
        }
        const objectString = JSON.stringify(obj);
        this.$copyText(objectString)
          .then((res) => {
            // this.$refs.addressInput.select(); // 实现选中效果
            this.$message.success("复制成功!");
          })
          .catch((err) => {
            this.$message.error("该浏览器不支持自动复制, 请手动复制");
          })
      }
    },

最终结果为{"地址":"https://www.baidu.com/","用户名":"张三","密码":"123"},,win+v剪贴板上也会存在

相关推荐
叶浩成5203 分钟前
手写chatGPT——fetch解析text/event-stream会话流并逐字回显到页面——js技能提升
开发语言·javascript·ecmascript
OpenTiny社区12 分钟前
OpenTiny HUICharts 正式开源发布,一个简单、易上手的图表组件库
前端·vue.js·开源·opentiny
@PHARAOH35 分钟前
WHAT - xmlhttprequest vs fetch vs wretch
前端·javascript·网络·http·fetch
解道Jdon43 分钟前
宏编程:C++宏、Rust宏和Lisp宏比较
javascript·reactjs
我不当帕鲁谁当帕鲁1 小时前
web浏览器播放rtsp视频流,海康监控API
前端·node.js
Leo_DLi1 小时前
Uncaught (in promise) ReferenceError: SharedArrayBuffer is not defined
前端·javascript·vue.js
七宝文1 小时前
React前端面试每日一试 6.空标签(Fragment)<></>是什么?它有什么作用?
前端·react.js·面试·前端框架
wrx繁星点点1 小时前
线程相关个人笔记总结
java·前端·jvm·spring boot·算法·spring·maven
RyzenVega1 小时前
Vue3 + JS项目配置ESLint Pretter
前端·javascript·vue.js
托尼沙滩裤1 小时前
【Vue】组件设计与状态管理优化
前端·javascript·vue.js