前端技术之:如何在Vue中使用clipboard.js复制服务端数据

本文详细介绍了如何在Vue项目中利用Clipboard.js库实现元素点击复制链接的功能,包括创建点击对象、引入和配置Clipboard.js、监听操作事件及销毁实例等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一步 创建点击对象页面元素,并绑定业务数据。

<el-button type="text" size="mini" class="copy-button"

  :data-resource-type="scope.data.resource_type"

  :data-resource-id="scope.data.resource_id">

  复制链接

</el-button>

 

第二步 引入clipboard.js。

 

import ClipboardJS from 'clipboard';

 

第三步 创建ClipboardJS对象实例。


mounted() {

  this.clipboard = new ClipboardJS('.copy-button', {

    text: () => this.copyLink

  });



  ...

}

 

第四步:替换clipboard对象实例的默认的onClick事件。

mounted() {

  ...

  const that = this;

  const oldOnClick = this.clipboard.onClick;

  this.clipboard.onClick = function onClick(e) {

    const resource_type = e.delegateTarget.getAttribute('data-resource-type');

    const resource_id = e.delegateTarget.getAttribute('data-resource-id');

    console.log('resource_type, resource_id is', resource_type, resource_id)

    that.$axios

      .post(APIS.Link, {

        type: 'h5_ugc_detail',

        params: {ugc_id: resource_id, ugc_type: resource_type},

        _csrf: that.$store.state.csrfToken

      })

      .then(res => {

        that.copyLink = res.data.data.link;

        oldOnClick.bind(that.clipboard)(e);

      })

      .catch(err => {

      });

  };



  ...

}

 

第五步:监听并处理操作成功与失败事件。

mounted() {

  ...


  this.clipboard.on('success', this.clipOptions.success);

  this.clipboard.on('error', this.clipOptions.error);

}

其中clipOptions类似如下:

computed: {

  clipOptions() {

    return {

      success: (e) => {

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

      },

      error: () => {

        this.$message.error('复制失败');

      }

    };

  },

  ...

}

 

第六步:vue生命周期结束时,销毁clipboard对象。

unmounted() {

  this.clipboard && this.clipboard.destroy();

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值